diff -Nru astyle-1.24/build/gcc/Makefile astyle-2.01/build/gcc/Makefile --- astyle-1.24/build/gcc/Makefile 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/build/gcc/Makefile 2010-11-29 17:28:18.000000000 +0000 @@ -15,35 +15,52 @@ # NOTE for java compiles the environment variable $JAVA_HOME must be set # example: export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.00 ifndef JAVA_HOME - JAVA_HOME = /usr/lib/jvm/java-6-sun-1.6.0.16 + JAVA_HOME = /usr/lib/jvm/default-java endif # set prefix if not defined on the command line ifndef prefix prefix=/usr endif -SYSCONF_PATH=$(prefix)/share/astyle +SYSCONF_PATH=$(prefix)/share/doc/astyle +# the path was changed in release 2.01 +# SYSCONF_PATH_OLD may be removed at the appropriate time +SYSCONF_PATH_OLD=$(prefix)/share/astyle # define macros bindir = bin objdir = obj ipath=$(prefix)/bin CBASEFLAGS = -W -Wall -fno-rtti -fno-exceptions -JAVAINCS = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux +JAVAINCS = -I$(JAVA_HOME)/include CXX = g++ INSTALL=install -o $(USER) -g $(USER) ################################################## # define compile options for each build -CFLAGS = -DNDEBUG -O3 $(CBASEFLAGS) -CFLAGSd = -g $(CBASEFLAGS) -CFLAGSs = -DNDEBUG -DASTYLE_LIB -O3 -fpic $(CBASEFLAGS) -CFLAGSsd = -DASTYLE_LIB -g -fpic $(CBASEFLAGS) -CFLAGSa = -DNDEBUG -DASTYLE_LIB -O3 $(CBASEFLAGS) -CFLAGSad = -DASTYLE_LIB -g $(CBASEFLAGS) -CFLAGSsj = -DNDEBUG -DASTYLE_JNI -O3 -fpic $(CBASEFLAGS) $(JAVAINCS) -CFLAGSsjd = -DASTYLE_JNI -g -fpic $(CBASEFLAGS) $(JAVAINCS) +ifdef CFLAGS + CFLAGSr = -DNDEBUG $(CBASEFLAGS) $(CFLAGS) + CFLAGSd = -g $(CBASEFLAGS) $(CFLAGS) +else + CFLAGSr = -DNDEBUG -O3 $(CBASEFLAGS) + CFLAGSd = -g $(CBASEFLAGS) +endif +CFLAGSs = -DASTYLE_LIB -fpic $(CFLAGSr) +CFLAGSsd = -DASTYLE_LIB -fpic $(CFLAGSd) +CFLAGSa = -DASTYLE_LIB $(CFLAGSr) +CFLAGSad = -DASTYLE_LIB $(CFLAGSd) +CFLAGSsj = -DASTYLE_JNI -fpic $(CFLAGSr) $(JAVAINCS) +CFLAGSsjd = -DASTYLE_JNI -fpic $(CFLAGSd) $(JAVAINCS) + +# define link options +ifdef LDFLAGS + LDFLAGSr = $(LDFLAGS) + LDFLAGSd = $(LDFLAGS) +else + LDFLAGSr = -s + LDFLAGSd = +endif # object files are built from the source list $(SRC) # a suffix is added for each build @@ -61,7 +78,7 @@ # OBJ $(objdir)/%.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGS) -c -o $@ $< + $(CXX) $(CFLAGSr) -c -o $@ $< # OBJd $(objdir)/%_d.o: %.cpp astyle.h astyle_main.h @@ -104,25 +121,25 @@ release: astyle astyle: $(OBJ) @ mkdir -p $(bindir) - $(CXX) -s -o $(bindir)/$@ $^ + $(CXX) $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo debug: astyled astyled: $(OBJd) @ mkdir -p $(bindir) - $(CXX) -o $(bindir)/$@ $^ + $(CXX) $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo shared: libastyle.so libastyle.so: $(OBJs) @ mkdir -p $(bindir) - $(CXX) -shared -s -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo shareddebug: libastyled.so libastyled.so: $(OBJsd) @ mkdir -p $(bindir) - $(CXX) -shared -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo static: libastyle.a @@ -140,13 +157,13 @@ java: libastylej.so libastylej.so: $(OBJsj) @ mkdir -p $(bindir) - $(CXX) -shared -s -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo javadebug: libastylejd.so libastylejd.so: $(OBJsjd) @ mkdir -p $(bindir) - $(CXX) -shared -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo all: release debug shared shareddebug static staticdebug @@ -158,17 +175,24 @@ cleanobj: rm -f $(objdir)/*.o - + install: $(INSTALL) -m 755 -d $(ipath) @$(INSTALL) -m 755 $(bindir)/astyle $(ipath) $(INSTALL) -m 755 -d $(SYSCONF_PATH) + @mkdir -p $(SYSCONF_PATH)/html; @for files in ../../doc/*.html ../../doc/*.css; \ do \ - $(INSTALL) -m 644 $$files $(SYSCONF_PATH); \ + $(INSTALL) -m 644 $$files $(SYSCONF_PATH)/html; \ done + @if [ -d $(SYSCONF_PATH_OLD) ]; then \ + rm -rf $(SYSCONF_PATH_OLD); \ + fi uninstall: rm -f $(ipath)/astyle rm -rf $(SYSCONF_PATH) + @if [ -d $(SYSCONF_PATH_OLD) ]; then \ + rm -rf $(SYSCONF_PATH_OLD); \ + fi diff -Nru astyle-1.24/build/intel/Makefile astyle-2.01/build/intel/Makefile --- astyle-1.24/build/intel/Makefile 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/build/intel/Makefile 2010-11-29 17:28:18.000000000 +0000 @@ -1,5 +1,16 @@ -# Make file for Intel compiler on Linux +# Make file for Intel compiler on Linux or compatible OS # The license.html file describes the conditions under which this software may be distributed. +# +# Before running "make" the COMPILER environment variables must be set. +# The file iccvars.sh should have been copied to /usr/sbin. +# To set the environment variables "source" the compiler environment script: +# source iccvars.sh +# where is ia32, intel64, or ia64. +# Refer to the install instructions for details. +# +# IF YOU GET AN ERROR MESSAGE: +# *** No rule to make target `obj/astyle_main.o', needed by `astyle'. +# SEE THE ABOVE INSTRUCTIONS. # list of source files SRC = astyle_main.cpp \ @@ -15,14 +26,17 @@ # NOTE for java compiles the environment variable $JAVA_HOME must be set # example: export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.00 ifndef JAVA_HOME - JAVA_HOME = /usr/lib/jvm/java-6-sun-1.6.0.16 + JAVA_HOME = /usr/lib/jvm/default-java endif # set prefix if not defined on the command line ifndef prefix prefix=/usr endif -SYSCONF_PATH=$(prefix)/share/astyle +SYSCONF_PATH=$(prefix)/share/doc/astyle +# the path was changed in release 2.01 +# SYSCONF_PATH_OLD may be removed at the appropriate time +SYSCONF_PATH_OLD=$(prefix)/share/astyle # define macros bindir = bin @@ -32,21 +46,35 @@ # -no-multibyte-chars is a temporary compiler bug work-around, http://software.intel.com/en-us/forums/intel-c-compiler/topic/56258 # if the intel compiler version doesn't support the current GCC headers use -gxx-name=g++-4.x where x is a previous GCC compiler CBASEFLAGS = -w2 -Wall -fno-rtti -fno-exceptions -vec-report0 -no-multibyte-chars -JAVAINCS = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux +JAVAINCS = -I$(JAVA_HOME)/include CXX = icpc INSTALL=install -o $(USER) -g $(USER) ################################################## # define compile options for each build -CFLAGS = -DNDEBUG -O3 $(CBASEFLAGS) -CFLAGSd = -g $(CBASEFLAGS) -CFLAGSs = -DNDEBUG -DASTYLE_LIB -O3 -fpic $(CBASEFLAGS) -CFLAGSsd = -DASTYLE_LIB -g -fpic $(CBASEFLAGS) -CFLAGSa = -DNDEBUG -DASTYLE_LIB -O3 $(CBASEFLAGS) -CFLAGSad = -DASTYLE_LIB -g $(CBASEFLAGS) -CFLAGSsj = -DNDEBUG -DASTYLE_JNI -O3 -fpic $(CBASEFLAGS) $(JAVAINCS) -CFLAGSsjd = -DASTYLE_JNI -g -fpic $(CBASEFLAGS) $(JAVAINCS) +ifdef CFLAGS + CFLAGSr = -DNDEBUG $(CBASEFLAGS) $(CFLAGS) + CFLAGSd = -g $(CBASEFLAGS) $(CFLAGS) +else + CFLAGSr = -DNDEBUG -O3 $(CBASEFLAGS) + CFLAGSd = -g $(CBASEFLAGS) +endif +CFLAGSs = -DASTYLE_LIB -fpic $(CFLAGSr) +CFLAGSsd = -DASTYLE_LIB -fpic $(CFLAGSd) +CFLAGSa = -DASTYLE_LIB $(CFLAGSr) +CFLAGSad = -DASTYLE_LIB $(CFLAGSd) +CFLAGSsj = -DASTYLE_JNI -fpic $(CFLAGSr) $(JAVAINCS) +CFLAGSsjd = -DASTYLE_JNI -fpic $(CFLAGSd) $(JAVAINCS) + +# define link options +ifdef LDFLAGS + LDFLAGSr = $(LDFLAGS) + LDFLAGSd = $(LDFLAGS) +else + LDFLAGSr = -static-intel -s + LDFLAGSd = -static-intel +endif # object files are built from the source list $(SRC) # a suffix is added for each build @@ -64,7 +92,7 @@ # OBJ $(objdir)/%.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGS) -c -o $@ $< + $(CXX) $(CFLAGSr) -c -o $@ $< # OBJd $(objdir)/%_d.o: %.cpp astyle.h astyle_main.h @@ -107,25 +135,25 @@ release: astyle astyle: $(OBJ) @ mkdir -p $(bindir) - $(CXX) -static-intel -s -o $(bindir)/$@ $^ + $(CXX) $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo debug: astyled astyled: $(OBJd) @ mkdir -p $(bindir) - $(CXX) -static-intel -o $(bindir)/$@ $^ + $(CXX) $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo shared: libastyle.so libastyle.so: $(OBJs) @ mkdir -p $(bindir) - $(CXX) -shared -static-intel -s -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo shareddebug: libastyled.so libastyled.so: $(OBJsd) @ mkdir -p $(bindir) - $(CXX) -shared -static-intel -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo static: libastyle.a @@ -143,13 +171,13 @@ java: libastylej.so libastylej.so: $(OBJsj) @ mkdir -p $(bindir) - $(CXX) -shared -static-intel -s -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ @ echo javadebug: libastylejd.so libastylejd.so: $(OBJsjd) @ mkdir -p $(bindir) - $(CXX) -shared -static-intel -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo all: release debug shared shareddebug static staticdebug @@ -161,17 +189,24 @@ cleanobj: rm -f $(objdir)/*.o - + install: $(INSTALL) -m 755 -d $(ipath) @$(INSTALL) -m 755 $(bindir)/astyle $(ipath) $(INSTALL) -m 755 -d $(SYSCONF_PATH) + @mkdir -p $(SYSCONF_PATH)/html; @for files in ../../doc/*.html ../../doc/*.css; \ do \ - $(INSTALL) -m 644 $$files $(SYSCONF_PATH); \ + $(INSTALL) -m 644 $$files $(SYSCONF_PATH)/html; \ done + @if [ -d $(SYSCONF_PATH_OLD) ]; then \ + rm -rf $(SYSCONF_PATH_OLD); \ + fi uninstall: rm -f $(ipath)/astyle rm -rf $(SYSCONF_PATH) + @if [ -d $(SYSCONF_PATH_OLD) ]; then \ + rm -rf $(SYSCONF_PATH_OLD); \ + fi diff -Nru astyle-1.24/build/intel/make.sh astyle-2.01/build/intel/make.sh --- astyle-1.24/build/intel/make.sh 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/build/intel/make.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -#!/bin/bash - -# Set the environment variables prior to invoking the compiler. -# For Intel compiler release 11.1 and higher. -# The script iccvars.sh should be copied to /usr/sbin. -# Assumes the ia32 compiler. Needs to be changed for the ia64 compiler. -# Instructions are in "getting_started_c.pdf" in the section -# "Starting the Compiler from the Command Line". - -if [ -e /usr/sbin/iccvars.sh ]; then - source /usr/sbin/iccvars.sh ia32 -fi - -make $1 $2 $3 $4 $5 $6 $7 $8 $9 diff -Nru astyle-1.24/debian/astyle.1 astyle-2.01/debian/astyle.1 --- astyle-1.24/debian/astyle.1 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/astyle.1 2011-05-12 13:16:18.000000000 +0000 @@ -1,4 +1,4 @@ -.TH ASTYLE 1 "March 13, 2007" astyle "User's Manual" +.TH ASTYLE 1 "February 21, 2011" astyle "User's Manual" .SH NAME astyle \- indentation and reformatting filters for C, C++, C#, Java @@ -9,8 +9,8 @@ \fBastyle\fR [\fIOPTIONS\fR] [\fIFILE1\fR] [\fIFILE2\fR] [\fI...\fR] .SH DESCRIPTION -\fBArtistic Style\fR (or \fBastyle\fR) is a reindenter and reformatter for -the C, C++, C# and Java programming languages. +\fBArtistic Style\fR (or \fBastyle\fR) is a source code indenter, formatter, +and beautifier for the C, C++, C# and Java programming languages. When indenting source code, we as programmers have a tendency to use both spaces and tab characters to create the wanted indentation. Moreover, some @@ -45,12 +45,12 @@ A default options file may be used to set your favorite source style. But, the command line options have precedence. The default options file can be \fB$HOME/.astylerc\fR, or be specified in the \fBARTISTIC_STYLE_OPTIONS\fR -environment variable or the \fB--options\fR command line option. +environment variable or the \fB\-\-options\fR command line option. .SH OPTIONS This program follows the usual GNU command line syntax, with long options -starting with two dashes (`--'). Long options must be written one at a time. -Short options (starting with '-') may be appended together. +starting with two dashes (`\-\-'). Long options must be written one at a time. +Short options (starting with '\-') may be appended together. Thus, \fB\-bps4\fR is the same as \fB\-b \-p \-s4\fR. @@ -92,16 +92,20 @@ switch statements and C++ class modifiers (public, private, protected). .TP \fB\-\-style=\fR\fIgnu\fR, \fB\-A\fR\fI7\fR -GNU style formatting/indenting. Uses brocken brackets and indented blocks. +GNU style formatting/indenting. Uses broken brackets and indented blocks. Indentation is 2 spaces. Extra indentation is added to blocks within a function. The opening bracket for namespaces, classes, and functions is not indented. .TP \fB\-\-style=\fR\fIlinux\fR, \fB\-A\fR\fI8\fR -Linux style formatting/indenting. Uses linux style brackets. Brackets are +Linux style formatting/indenting uses linux style brackets. Brackets are broken from namespace, class, and function definitions. Brackets are -attached to statements within a function. Indentation is 8 spaces. Also -known as Kernel Normal Form (KNF) style, this is the style used in the +attached to statements within a function. \fBIndentation\fR is 8 spaces. +\fBMinimum conditional indent\fR is 4 spaces, or one-half the spaces per indent +if a different setting is used. If you want to change the spaces per indent for +this style it will be easier to use the K&R style instead. + +Also known as Kernel Normal Form (KNF) style, this is the style used in the Linux kernel. .TP \fB\-\-style=\fR\fIhorstmann\fR, \fB\-A\fR\fI9\fR @@ -112,12 +116,12 @@ \fB\-\-style=\fR\fI1tbs\fR, \fB\-\-style=\fR\fIotbs\fR, \fB\-A\fR\fI10\fR "One True Brace Style" formatting/indenting uses linux style brackets and adds brackets to unbracketed one line conditional statements. The -option \fB\-\-add-one-line-brackets\fR can also be used with this style. +option \fB\-\-add\-one\-line\-brackets\fR can also be used with this style. .SS "Tab and Bracket Options:" If no indentation option is set, the default option of 4 spaces will be -used. Equivalent to \fB-s\fR4 \fB--indent=\fR\fIspaces=4\fR. If no brackets +used. Equivalent to \fB\-s\fR4 \fB\-\-indent=\fR\fIspaces=4\fR. If no brackets option is set, the brackets will not be changed. .TP @@ -130,7 +134,7 @@ Between 1 and 20. Not specifying # will result in a default assumption of 4 spaces per tab. .TP -\fB\-\-indent=\fR\fIforce-tab\fR, \fB\-\-indent=\fR\fIforce-tab=#\fR, \fB\-T\fR, \fB\-T\fR\fI#\fR +\fB\-\-indent=\fR\fIforce\-tab\fR, \fB\-\-indent=\fR\fIforce\-tab=#\fR, \fB\-T\fR, \fB\-T\fR\fI#\fR Indent using tab characters, assuming that each tab is # spaces long. Between 1 and 20. Force tabs to be used in areas astyle would usually prefer to use spaces (as in multi-line statements). Not specifying # will @@ -162,75 +166,76 @@ .SS "Indentation Options:" .TP -\fB\-\-indent-classes\fR, \fB\-C\fR +\fB\-\-indent\-classes\fR, \fB\-C\fR Indent 'class' blocks, so that the inner 'public:', 'protected:' and 'private:' headers are indented in relation to the class block. This option has no effect on Java and C# files. .TP -\fB\-\-indent-switches\fR, \fB\-S\fR +\fB\-\-indent\-switches\fR, \fB\-S\fR Indent 'switch' blocks, so that the inner 'case X:' headers are indented in relation to the switch block. The entire case block is indented. .TP -\fB\-\-indent-cases\fR, \fB\-K\fR +\fB\-\-indent\-cases\fR, \fB\-K\fR Indent 'case X:' lines, so that they are flush with their bodies. Case statements not enclosed in blocks are NOT indented. .TP -\fB\-\-indent-brackets\fR, \fB\-B\fR +\fB\-\-indent\-brackets\fR, \fB\-B\fR Add extra indentation to '{' and '}' block brackets. This is the option used for Whitesmith and Banner style formatting/indenting. If both \fB\-\-indent\-brackets\fR and \fB\-\-indent\-blocks\fR are used the result will be \fB\-\-indent\-blocks\fR. .TP -\fB\-\-indent-blocks\fR, \fB\-G\fR +\fB\-\-indent\-blocks\fR, \fB\-G\fR Add extra indentation to blocks \fBwithin a function\fR. The opening bracket for namespaces, classes, and functions is not indented. This is the option used for GNU style formatting/indenting. .TP -\fB\-\-indent-namespaces\fR, \fB\-N\fR +\fB\-\-indent\-namespaces\fR, \fB\-N\fR Add extra indentation to namespace blocks. This option has no effect on Java files. .TP -\fB\-\-indent-labels\fR, \fB\-L\fR +\fB\-\-indent\-labels\fR, \fB\-L\fR Indent labels so that they appear one indent less than the current indentation level, rather than being flushed completely to the left (which is the default). .TP -\fB\-\-indent-preprocessor\fR, \fB-w\fR +\fB\-\-indent\-preprocessor\fR, \fB\-w\fR Indent multi-line preprocessor definitions ending with a backslash. Should -be used with \fB\-\-convert-tabs\fR for proper results. Does a pretty good +be used with \fB\-\-convert\-tabs\fR for proper results. Does a pretty good job, but can not perform miracles in obfuscated preprocessor definitions. .TP -\fB\-\-indent-col1-comments\fR, \fB-Y\fR +\fB\-\-indent\-col1\-comments\fR, \fB\-Y\fR Indent C++ comments beginning in column one. By default C++ comments beginning in column one are not indented. This option will allow the comments to be indented with the code. .TP -\fB\-\-max-instatement-indent=\fR\fI#\fR, \fB-M\fR\fI#\fR +\fB\-\-max\-instatement\-indent=\fR\fI#\fR, \fB\-M\fR\fI#\fR Indent a maximum of # spaces in a continuous statement, relative to the previous line. Must be less than 80. The default value is 40. .TP -\fB\-\-min-conditional-indent=\fR\fI#\fR, \fB-m\fR\fI#\fR +\fB\-\-min\-conditional\-indent=\fR\fI#\fR, \fB\-m\fR\fI#\fR Indent a minimal # spaces in a continuous conditional belonging to a conditional header. Must be less than 40. The default value is \fBtwice the current indent\fR. .SS "Formatting options:" .TP -\fB\-\-break-blocks\fR, \fB-f\fR +\fB\-\-break\-blocks\fR, \fB\-f\fR Insert empty lines around header blocks (e.g. 'if', 'while'...). .TP -\fB\-\-break-blocks=\fR\fIall\fR, \fB-F\fR -Like \-\-break-blocks, except also insert empty lines +\fB\-\-break\-blocks=\fR\fIall\fR, \fB\-F\fR +Like \-\-break\-blocks, except also insert empty lines around closing headers (e.g. 'else', 'catch', ...). .TP -\fB\-\-break-closing-brackets\fR, \fB-y\fR, \fB\-\-brackets=\fR\fIbreak-closing\fR (deprecated) -Break brackets before closing headers (e.g. 'else', 'catch', ..). -Should be appended to \fB\-\-brackets\fR=attach, \fB\-\-brackets=\fR\fIlinux -or \fB\-\-brackets\fR=stroustrup. Closing header brackets are always broken -with broken brackets, indented blocks, and indented brackets. +\fB\-\-break\-closing\-brackets\fR, \fB\-y\fR +When used with \fB\-\-brackets\fR=attach, \fB\-\-brackets=\fR\fIlinux +or \fB\-\-brackets\fR=stroustrup, this breaks closing headers (e.g. \'else\', +\'catch\', ...) from their immediately preceding closing brackets. Closing +header brackets are always broken with broken brackets, horstmann brackets, +indented blocks, and indented brackets. .TP -\fB\-\-break-elseifs\fR, \fB\-e\fR +\fB\-\-break\-elseifs\fR, \fB\-e\fR Break "else if" header combinations into separate lines. This option has no effect if \fB\-\-keep\-one\-line\-statements\fR is used, the "else if" statements will remain as they are. @@ -238,49 +243,54 @@ If this option is NOT used, "else if" header combinations will be placed on a single line. .TP -\fB\-\-add-brackets\fR, \fB\-j\fR +\fB\-\-add\-brackets\fR, \fB\-j\fR Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...). The statement must be on a single line. The brackets will be added according to the currently requested predefined style or bracket type. If no style or bracket type is requested the brackets will be attached. If -\fB\-\-add-one-line-brackets\fR is also used the result will be one line +\fB\-\-add\-one\-line\-brackets\fR is also used the result will be one line brackets. .TP -\fB\-\-add-one-line-brackets\fR, \fB\-J\fR +\fB\-\-add\-one\-line\-brackets\fR, \fB\-J\fR Add one line brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...). The statement must be on a single line. -The option implies \fB--keep-one-line-blocks\fR and will not break the +The option implies \fB\-\-keep\-one\-line\-blocks\fR and will not break the one line blocks. .TP -\fB\-\-delete\-empty\-lines\fR, \fB-x\fR +\fB\-\-delete\-empty\-lines\fR, \fB\-x\fR Delete empty lines within a function or method. Empty lines outside of -functions or methods are NOT deleted. If used with \fB--break-blocks\fR +functions or methods are NOT deleted. If used with \fB\-\-break\-blocks\fR or \fB\-\-break\-blocks\fR=all it will delete all lines \fBexcept\fR the lines added by the \fB\-\-break\-blocks\fR options. .TP -\fB\-\-pad-paren\fR, \fB\-p\fR, \fB\-\-pad=\fR\fIparen\fR (deprecated) +\fB\-\-pad\-oper\fR, \fB\-p\fR +Insert space padding around operators. Any end of line comments will remain in +the original column, if possible. Note that there is no option to unpad. Once +padded, they stay padded. +.TP +\fB\-\-pad\-paren\fR, \fB\-P\fR Insert space padding around parenthesis on both the \fBoutside\fR and the \fBinside\fR. Any end of line comments will remain in the original column, if possible. .TP -\fB\-\-pad-paren-out\fR, \fB\-d\fR, \fB--pad=\fR\fIparen\-out\fR (deprecated) +\fB\-\-pad\-paren\-out\fR, \fB\-d\fR Insert space padding around parenthesis on the \fBoutside\fR only. Any end of line comments will remain in the original column, if possible. This can be used with \fB\-\-unpad\-paren\fR below to remove unwanted spaces. .TP -\fB\-\-pad\-paren\-in\fR, \fB-D\fR, \fB--pad=\fR\fIparen-in\fR (deprecated) +\fB\-\-pad\-paren\-in\fR, \fB\-D\fR Insert space padding around parenthesis on the \fBinside\fR only. Any end of line comments will remain in the original column, if possible. This can be used with \fB\-\-unpad\-paren\fR below to remove unwanted spaces. .TP -\fB\-\-pad\-header\fR, \fB-H\fR +\fB\-\-pad\-header\fR, \fB\-H\fR Insert space padding after paren headers only (e.g. 'if', 'for', 'while'...). Any end of line comments will remain in the original column, if possible. This can be used with -\fB--unpad-paren\fR to remove unwanted spaces. +\fB\-\-unpad\-paren\fR to remove unwanted spaces. .TP -\fB\-\-unpad\-paren\fR, \fB-U\fR, \fB\-\-unpad=\fR\fIparen\fR (deprecated) +\fB\-\-unpad\-paren\fR, \fB\-U\fR Remove extra space padding around parenthesis on the inside and outside. Any end of line comments will remain in the original column, if possible. This option can be used in combination with the paren padding options @@ -292,14 +302,14 @@ outside padding, and \fB\-\-pad\-paren\-in\fR to retain the inside padding. Using only \fB\-\-pad\-paren\-in\fR would not remove the outside padding. .TP -\fB\-\-keep-one-line-statements\fR, \fB\-o\fR, \fB\-\-one-line=\fR\fIkeep-statements\fR (deprecated) +\fB\-\-keep\-one\-line\-statements\fR, \fB\-o\fR Don't break complex statements and multiple statements residing on a single line. .TP -\fB\-\-keep-one-line-blocks\fR, \fB\-O\fR, \fB\-\-one-line=\fR\fIkeep-blocks\fR (deprecated) +\fB\-\-keep\-one\-line\-blocks\fR, \fB\-O\fR Don't break blocks residing completely on one line .TP -\fB\-\-convert-tabs\fR, \fB-c\fR +\fB\-\-convert\-tabs\fR, \fB\-c\fR Convert tabs to spaces in the non-indentation part of the line. The number of spaces inserted will maintain the spacing of the tab. The current setting for spaces per tab is used. It may not produce the expected results @@ -316,12 +326,12 @@ name. The spacing between the type and name will be preserved, if possible. This option is effective for C/C++ files only. .TP -\fB\-\-fill-empty-lines\fR, \fB-E\fR +\fB\-\-fill\-empty\-lines\fR, \fB\-E\fR Fill empty lines with the white space of their previous lines. .SS "Indentation modes:" The modes used for indentation are set by each file's extension, but it can -be overriden with the following options: +be overridden with the following options: .TP \fB\-\-mode=\fR\fIc\fR Indent a C or C++ source file (default). @@ -337,7 +347,7 @@ \fB\-\-suffix=\fR\fI####\fR Append the suffix \fI####\fR instead of '.orig' to original filename. .TP -\fB\-\-suffix=\fR\fInone\fR, \fB-n\fR +\fB\-\-suffix=\fR\fInone\fR, \fB\-n\fR Do not retain a backup of the original file. The original file is purged after it is formatted. .TP @@ -348,7 +358,7 @@ Disable the default options file. Only the command-line parameters will be used. .TP -\fB\-\-recursive\fR, \fB-r\fR, \fB-R\fR +\fB\-\-recursive\fR, \fB\-r\fR, \fB\-R\fR For each directory in the command line, process all subdirectories recursively. When using the recursive option the file name statement should contain a wildcard. The filepath and name should be placed in @@ -374,24 +384,24 @@ The filepath and name may be placed in double quotes (e.g. \fB\-\-exclude=\fR"foo bar.cpp"). .TP -\fB\-\-errors-to-stdout\fR, \fB-X\fR +\fB\-\-errors\-to\-stdout\fR, \fB\-X\fR Print errors and help information to standard-output rather than to standard-error. .TP -\fB\-\-preserve-date\fR, \fB-Z\fR +\fB\-\-preserve\-date\fR, \fB\-Z\fR Preserve the original file's date and time modified. The date and time modified will not be changed in the formatted file. This option is not effective if redirection is used. .TP -\fB\-\-verbose\fR, \fB-v\fR +\fB\-\-verbose\fR, \fB\-v\fR Verbose display mode. Display optional information, such as release number and statistical data. .TP -\fB\-\-formatted\fR, \fB-Q\fR +\fB\-\-formatted\fR, \fB\-Q\fR Formatted files display mode. Display only the files that have been formatted. Do not display files that are unchanged. .TP -\fB\-\-quiet\fR,\fB-q\fR +\fB\-\-quiet\fR,\fB\-q\fR Quiet display mode. Suppress all output except error messages. .TP \fB\-\-lineend=\fR\fIwindows\fR, \fB\-z\fR\fI1\fR @@ -416,7 +426,7 @@ following order: .TP .B 1. -The contents of the file indicated by the --options= command line option; +The contents of the file indicated by the \-\-options= command line option; .B 2. The contents of the \fIARTISTIC_STYLE_OPTIONS\fR environment variable if it exists. @@ -431,21 +441,21 @@ .P If a default options file is found, the options in this file will be parsed BEFORE the command-line options. This option file lookup can be disabled -by specifying --options=none on the command line. +by specifying \-\-options=none on the command line. .P Long options within the default option file may be written without the -preliminary '--', but short options require the preceding '-'. Lines within +preliminary '\-\-', but short options require the preceding '\-'. Lines within the options file that begin with '#' are considered line-comments. .SH VERSION -1.23 +2.01 .SH "SEE ALSO" .BR indent(1) -.I http://astyle.sourceforge.net +.I http://astyle.sourceforge.net/ .br -.I http://www.sourceforge.net/projects/astyle +.I http://www.sourceforge.net/projects/astyle/ .br .I http://packages.debian.org/astyle @@ -457,4 +467,5 @@ \fIhttp://www.netmeister.org/misc/m2p2/index.html\fR for details. Minor modifications by Luca Filipozzi . Updated on -August 2009 by Margarita Manterola +August 2009 by Margarita Manterola . Updated on April +2010, February 2011 by Matteo Cypriani . diff -Nru astyle-1.24/debian/changelog astyle-2.01/debian/changelog --- astyle-1.24/debian/changelog 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/changelog 2011-05-12 13:16:18.000000000 +0000 @@ -1,6 +1,19 @@ +astyle (2.01-1) unstable; urgency=low + + * New upstream release. (Closes: #616710) + * Update package description. + * Update manpage. + * Bump Standards-Version to 3.9.2 + * Convert debian/copyright to DEP5 format. + * Switch to 3.0 (quilt) format. + * Add VCS fields. + * Avoid unneeded dependency on libgcc_s. + + -- Matteo Cypriani Thu, 12 May 2011 15:15:13 +0200 + astyle (1.24-1) unstable; urgency=low - * New upstream release. + * New upstream release. - Fix comma separated initialization bug (Closes: #569170) * Updated the manpage to reflect the new options. diff -Nru astyle-1.24/debian/control astyle-2.01/debian/control --- astyle-1.24/debian/control 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/control 2011-05-12 13:16:18.000000000 +0000 @@ -4,12 +4,16 @@ Build-Depends: debhelper (>= 5.0) Maintainer: Margarita Manterola Uploaders: Matteo Cypriani -Standards-Version: 3.8.4 +Standards-Version: 3.9.2 Homepage: http://astyle.sourceforge.net/ +Vcs-Git: git://git.debian.org/git/collab-maint/astyle.git +Vcs-Browser: http://git.debian.org/?p=collab-maint/astyle.git Package: astyle Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends} Description: Source code indenter for C++/C/Java/C# source code - Artistic Style is a reindenter and reformatter of C++, C, Java or C# - source code. + Artistic Style is a source code indenter, formatter, and beautifier + for the C, C++, C# and Java programming languages. + . + This package contains the command line tool. diff -Nru astyle-1.24/debian/copyright astyle-2.01/debian/copyright --- astyle-1.24/debian/copyright 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/copyright 2011-05-12 13:16:18.000000000 +0000 @@ -1,23 +1,29 @@ -The original source code was downloaded from http://astyle.sourceforge.net/ +Format: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=166 +Upstream-Name: Artistic Style +Upstream-Contact: Jim Pattee +Source: http://astyle.sourceforge.net/ Files: * -Copyright: © 1998-2004 Tal Davidson , - © 2005-2006 Martin Baute - © 2006-2010 Jim Pattee +Copyright: + 1998-2004 Tal Davidson + 2005, 2006 Martin Baute + 2006-2010 Jim Pattee License: LGPL-3+ - Artistic Style is free software: you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public License - as published by the Free Software Foundation, either version 3 of - the License, or (at your option) any later version. Files: debian/* -Copyright: © 1999 Brian M. Almeida - © 1999-2001 Sean 'Shaleh' Perry - © 2001-2003 Luca Filipozzi - © 2004-2009 Margarita Manterola - © 2010 Matteo Cypriani , - Margarita Manterola +Copyright: + 1999 Brian M. Almeida + 1999-2001 Sean 'Shaleh' Perry + 2001-2003 Luca Filipozzi + 2004-2011 Margarita Manterola + 2010, 2011 Matteo Cypriani License: LGPL-3+ -On Debian machines, the full text of the GNU Lesser General Public -License can be found in the file /usr/share/common-licenses/LGPL-3. +License: LGPL-3+ + This program is free software: you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public License + as published by the Free Software Foundation, either version 3 of + the License, or (at your option) any later version. + . + On Debian machines, the full text of the GNU Lesser General Public + License can be found in the file /usr/share/common-licenses/LGPL-3. diff -Nru astyle-1.24/debian/NEWS astyle-2.01/debian/NEWS --- astyle-1.24/debian/NEWS 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/NEWS 2011-05-12 13:16:18.000000000 +0000 @@ -1,6 +1,16 @@ +astyle (2.01-1) unstable; urgency=low + + Here is an extract from the release notes: + With a new Artistic Style release some unchanged source files will be + formatted because of changes to Artistic Style. You may want to format + your source before making program changes in order to bring it up to + date. + + -- Matteo Cypriani Mon, 21 Feb 2011 16:30:22 +0100 + astyle (1.24-1) unstable; urgency=low - Beware! This new astyle version once more fixes and improves many + Beware! This new astyle version once more fixes and improves many options, but your code could be re-indented even if you changed nothing. -- Matteo Cypriani Thu, 08 Apr 2010 20:40:00 +0200 diff -Nru astyle-1.24/debian/rules astyle-2.01/debian/rules --- astyle-1.24/debian/rules 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/rules 2011-05-12 13:16:18.000000000 +0000 @@ -3,6 +3,10 @@ # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 +# Avoid unneeded library dependencies +LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS) +LDFLAGS += -Wl,--as-needed + # Flags for debugging, and original flags from the program. CXXFLAGS = -g -Wall -Wno-sign-compare diff -Nru astyle-1.24/debian/source/format astyle-2.01/debian/source/format --- astyle-1.24/debian/source/format 2011-05-13 07:00:49.000000000 +0000 +++ astyle-2.01/debian/source/format 2011-05-13 07:00:49.000000000 +0000 @@ -1 +1 @@ -1.0 +3.0 (quilt) diff -Nru astyle-1.24/doc/astyle.html astyle-2.01/doc/astyle.html --- astyle-1.24/doc/astyle.html 2010-01-30 19:55:38.000000000 +0000 +++ astyle-2.01/doc/astyle.html 2010-11-29 17:28:18.000000000 +0000 @@ -12,6 +12,7 @@ + + + + @@ -17,6 +29,100 @@

 

+

+ Artistic Style Survey

+ +

+ This release has a survey that will be used to determine how Artistic Style is used and to set priorities for + future enhancements. It consists of less than 25 questions, most of which are multiple choice. To take the survey + you should have used Artistic Style long enough to be familiar with the options.

+

+ The survey contains general questions about your programming environment and your use of Artistic Style and its + various options. At the end are questions about changes you would like to see and complaints you may have. No + personal information is asked for or collected.

+

+ Please + take the survey to help determine the priorities for Artistic Style. Survey results will be posted on + this website at the end of the survey.

+ +

+

+ Artistic Style 2.01  (November 2010)

+

+ +

+ With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date.

+

+ A new feature at SourceForge is download maps that show a list of downloads by country. It is available from the + top menu at Develop > Download Stats (Beta), and clicking on the "top country" area. The list of downloads + shows about 75% of Artistic Style downloads are from non English speaking countries. This release is the start of the internationalization of Artistic Style.

+

+ Artistic Style now sets the native local so that characters from the user’s native language will be recognized + in directory names and file names. Artistic Style for Windows has also been changed to use the native locale. + For Linux systems using UTF-8 locales, characters from any language will be recognized and any combination of + languages can be used. For Windows, only languages recognized by the native codepage can be used. For example, + the English locale (codepage 1252) also has French, German, Italian, Portuguese, Spanish, plus several other languages. + Other locals, such as Chinese and Japanese, only support one language. Unicode was not used due to the varying + degree of support by different compilers for console applications.

+

+ The locale setting also affects the way numbers are displayed. Language translations may be provided in a future + release.  +

+

+ This is a major release (2.01) because of the internationalization and changes that will occur in the next couple + of releases. Future releases will contain a major change to the bracket options and a rewrite of the file access + method. Some of the requested changes require looking at blocks of code instead of single lines. The current program + has been patched to do this but a rewrite of the file input is needed. These are both major changes but with the + new test framework in place they should be manageable.

+

+ There has been a change to the ‑‑min‑conditional‑indent option. Instead of using the number + of spaces it now uses a code expressed in number of indents. This will allow the option to be set independently + of the spaces per indent. If you are using the default setting of two indents, or a setting of zero indents, there + is no change necessary to the input. Otherwise, check the documentation for the new codes.

+

+ The --style=linux has been changed to ALWAYS use a minimum conditional indent of one-half the indent length. This + is in the style definition and cannot be changed. If you do not want this setting use the K&R style instead. +

+

+ The MFC macros BEGIN_DISPATCH_MAP, BEGIN_EVENT_MAP, and BEGIN_PROPPAGEIDS are now formatted. +

+

+ Checksum verification has been added to source file output that will help assure that no code has been duplicated + or omitted. This is effective only in the debug configuration used for testing.

+

+ The test framework has been changed from UnitTest++ to Google Test, which is actively maintained, has a mock object framework (Google Mock), and good documentation. Regression and system + testing have been automated with Python scripts. Python has also been used for class verification checks and other + repetitive procedures.

+

+ If you use Visual Studio C++ Express the 2010 release has the ability to create x64 code. But you must use Vista + or Windows 7 and need to install the .NET Framework SDK. I have created a brief instruction page here.

+

+ Thanks to Matthew Woehlke, Chris Schwarz, Chang Jiang, and Arseny Solokha for their contributions.

+ +

+ Developers

+ +

+ On the library build of Artistic Style, the second argument of the fpError typedef and the javaErrorHandler declaration + has been changed from "char*" to "const char*". This could cause a compile error if not changed in the source + statements.

+

+ There has been a change in the ‑‑min‑conditional‑indent option. Instead of using number + of spaces to indent it now uses a code expressed in number of indents. In the past this option was a problem because + it was also affected by changes in indent length. With this release there is only one variable affected. The option + is not affected by changes in indent length. The minimum conditional indent length is computed automatically by + ASFormatter after all the options have been processed. Refer to the code in astyle_main.cpp to see how the option + is processed.

+

+ The --style=linux has been changed to ALWAYS use a minimum conditional indent of one-half the indent length. The + option is set in the function fixOptionVariableConflicts.

+

+ The use of locales affects only the command line build.

+

Artistic Style 1.24  (February 2010)

@@ -30,8 +136,8 @@ space and aligning brackets. The "Tab and Bracket Options" section in the documentation contains the details. To accommodate Hostmann brackets the "none mode" brackets will now allow run-in statements. Array formatting has been changed to format run-in statements when required. There have been some general improvements - to array formatting. The minimum value for spaces per tab was changed from one to two. The example programs in the "Developer - Information" section have been changed to Horstmann brackets.

+ to array formatting. The minimum value for spaces per tab was changed from one to two. The example programs in + the "Developer Information" section have been changed to Horstmann brackets.

Two new options, ‑‑add‑brackets (-j) and ‑‑add‑one‑line‑brackets (-J), will add brackets to unbracketed one line conditional statements. The ‑‑add-brackets will add @@ -41,8 +147,8 @@ and will not break single line blocks.

- The above options allow two new predefined styles. Horstmann style, ‑‑style=horstmann - (-A9), uses Horstmann brackets and three spaces per indent. The so called "One True Brace Style", ‑‑style=1tbs + The above options allow two new predefined styles. Horstmann style, ‑‑style=horstmann (-A9), uses + Horstmann brackets and three spaces per indent. The so called "One True Brace Style", ‑‑style=1tbs or ‑‑style=otbs (-A10), uses linux brackets and the option ‑‑add‑brackets. The basic criteria for most predefined styles were obtained from the Indent Style discussion at Wikipedia. The "Predefined Style Options" section in the documentation contains the @@ -56,8 +162,8 @@ 'while'...). To remove any unwanted current space padding, use the option ‑‑unpad‑paren (‑U). If both ‑‑pad‑header and ‑‑unpad‑paren are used, the headers will be padded and the padding will be removed from other parens. This has required a change to the default formatting of paren - headers. They will now be left unchanged instead of automatically inserting space padding, unless the - new option is requested.

+ headers. They will now be left unchanged instead of automatically inserting space padding, unless the new option + is requested.

New options --align-pointer=type (-k1), ‑‑align‑pointer=middle (-k2), and ‑‑align‑pointer=name (-k3) will attach a pointer or reference operator (* or &) to either the operator type (left), operator name @@ -78,8 +184,8 @@ Default line end processing has been improved to always output consistent line ends. It will use the line ends that are most frequently used in the input.

- The Stroustroup predefined style has been changed to use 5 spaces per indent. This is the indentation used in - the book "The C++ Programming Language" by Bjarne Stroustrup.

+ The Stroustrup predefined style has been changed to use 5 spaces per indent. This is the indentation used in the + book "The C++ Programming Language" by Bjarne Stroustrup.

The minimum conditional indent for the Linux predefined style has been changed to 4, or one-half the indent-length. The previous minimum conditional indent was 16 (2 indents). The new value corresponds to the soft tab in the style @@ -123,10 +229,10 @@ The Intel compiler for Linux, release 11.1, has a new procedure for compiles. Read the new "Install Information" before using this compiler release.

- There is now a Subversion repository for Artistic Style. A new Subversion web page describes how to check-out the files. - The source code is under development and some changes take several weeks to complete. And the intermediate source - files have not been through the extensive system tests that are done before each release. Use reasonable precautions - when using source code from the repository.

+ There is now a Subversion repository for Artistic Style. A new Subversion web page describes how to check-out + the files. The source code is under development and some changes take several weeks to complete. And the intermediate + source files have not been through the extensive system tests that are done before each release. Use reasonable + precautions when using source code from the repository.

SourceForge recently made changes to their website which caused a few problems. The web page links should be fixed with this release. It seems that some bug reports may have been lost. If you have submitted a report that has @@ -156,15 +262,16 @@ title="open new window">jimp03.zxq.net

The options --lineend=windows (-z1), --lineend=linux (-z2), and --lineend=macold (-z3) apply only - to the console build. It was not included in the developer builds because developers usually have their - own method for handling line ends.

+ to the console build. It was not included in the developer builds because developers usually have their own method + for handling line ends.

The option --break-closing-brackets has been moved from Bracket Options to Formatting Options. It was being mistaken for a bracket type, which it is not.

- Rejecting a file for  UTF-16 or UTF-32 bit encoding apply only to the console build. Some class libraries, such - as wxWidgets (and probably Qt), have the methods to convert the files to UTF-8. The handling for these types of - files must be determined by the individual applications.

+ Rejecting a file for  UTF-16 or UTF-32 bit encoding apply only to the console build. Some class libraries, + such as wxWidgets (and probably Qt), have the methods to convert the files to UTF-8. The handling for these types + of files must be determined by the individual applications. +

There has been an additional variable, formattingStyle, added to the ASFormatter class. This is now the ONLY option that needs to be set to define the style. Setting the individual options is no longer necessary. The individual @@ -408,7 +515,7 @@ there have been over 80 items removed from the bug report. There have been many more fixes which were not reported but were discovered while testing. The new options in this release exposed many unreported formatting problems. I will try to fix the ones remaining in the next two or three releases. Some of them will be difficult to fix. - See the Release Notes for a complete list of changes.

+ See the Release Notes for a complete list of changes.

Starting with this release, if a file is not changed by Artistic Style a new file and a backup file are not created. A "make" will not recompile the unchanged file and it will not be committed to a revision control @@ -437,8 +544,7 @@

When processing directories recursively it is sometimes necessary to exclude certain files or directories. This can be done using a new exclude (‑‑exclude=file‑or‑directory) option. There is no short - option. Multiple exclude statements are allowed. The Other Options section - of the documentation contains the details.

+ option. Multiple exclude statements are allowed. The Other Options section of the documentation contains the details.

It is always a good idea to create a backup for files that have been formatted. This can cause a problem in that it creates a lot of excess files in your source directories. There are now new script files available that will @@ -446,19 +552,18 @@ is a batch file for Windows and a shell script for everyone else. They are available in the Scripts section of the home page.

- There is a new Links page that lists programs using Artistic Style. In general, they - seem to be good quality software.

+ There is a new Links page that lists programs using Artistic Style. In general, they seem to be good quality software.

- If you are using a development environment to compile Artistic Style, be sure to read the - Compiler Options section in the Install Information. In particular, you should define NDEBUG in the Release - compile to remove the assert statements. There are quite a few of these and they will slow down processing if - NDEBUG is not used. The assert statements are necessary due to the nature of the program. Also, when reporting - bugs it is a good idea to log in first. Occasionally, more information is needed on a problem. If the poster did - not log in there is no way to contact them.

+ If you are using a development environment to compile Artistic Style, be sure to read the Compiler Options section + in the Install Information. In particular, you should define NDEBUG in the Release compile to remove the assert + statements. There are quite a few of these and they will slow down processing if NDEBUG is not used. The assert + statements are necessary due to the nature of the program. Also, when reporting bugs it is a good idea to log + in first. Occasionally, more information is needed on a problem. If the poster did not log in there is no way + to contact them.

A Java Native Interface has been added for Java developers. This will allow an Artistic Style shared library (DLL) to be called from a Java program. A shared library (Dll) using the Java interface can still be called from C, - C++, or C# programs. There is a sample program in the Developer Information.

+ C++, or C# programs. There is a sample program in the Developer Information.

Developers using Artistic Style in another project should be aware that there are two new functions that have been added to the ASStreamIterator class (peekNextLine() and peekReset()). These will have to be coded @@ -488,7 +593,7 @@ will be broken from lines with comments without bringing the comments with them. All comments will remain in their original column, if possible. The formatting of empty blocks was fixed. The BracketType definition was expanded and the bracket types are now correctly identified. There are several formatting fixes for Java files. See the - Release Notes for a complete list of changes.

+ Release Notes for a complete list of changes.

A new option, --preserve-date (-Z), has been added. This will retain the date modified of the original file in the new formatted file. Otherwise the new file will contain the current date.

@@ -509,8 +614,8 @@ platform. The main difference in platforms is the build directory and the line endings. The source code and documentation are the same for all packages.

- There are new instructions about optimizing compiler options in the Install Instructions. - If you are compiling using a development environment you may want to read them.

+ There are new instructions about optimizing compiler options in the Install Instructions. If you are compiling + using a development environment you may want to read them.

If you have broken brackets with comments attached to the opening bracket instead of the previous line, do the following before formatting again with broken brackets. Use the current Artistic Style release (1.21). diff -Nru astyle-1.24/doc/notes.html astyle-2.01/doc/notes.html --- astyle-1.24/doc/notes.html 2010-01-30 19:55:38.000000000 +0000 +++ astyle-2.01/doc/notes.html 2010-11-29 17:28:18.000000000 +0000 @@ -17,1094 +17,1167 @@

 

-

- Artistic Style 1.24  (February 2010)

+

+ Artistic Style 2.01  (November 2010)

    -
  • Add new option ‑‑brackets=horstmann (-g) to place run‑in statements on the same line as an opening bracket. +
  • Add recognition of language characters supported by the native locale.
  • +
  • Add formatting of numbers according to the native locale.
  • +
  • Add checksum verification to source file output.
  • +
  • Add formatting of MFC macros BEGIN_DISPATCH_MAP, BEGIN_EVENT_MAP, and BEGIN_PROPPAGEIDS.
  • +
  • Add error message if --recursive is used without a wildcard in the file name.
  • +
  • Add private (unusable) copy constructors for classes with dynamic allocation.
  • +
  • Add error message if the "cin" stream cannot be processed because a pipe is used.
  • +
  • Improve recognition of ARRAY_TYPE brackets.
  • +
  • Improve formatting of multi-line comments when the number of leading spaces must be changed.
  • +
  • Improve formatting of embedded SQL when the number of leading spaces must be changed.
  • +
  • Improve recognition of C++ templates.
  • +
  • Change --style=linux to always use a minimum conditional indent of one-half the indent length.
  • +
  • Change --pad-oper to pad operators in block parens.
  • +
  • Change to indent OpenMP pragmas with the code.
  • +
  • Change to display all (instead of one) option errors before abort.
  • +
  • Change the second argument of the fpError typedef from "char*" to "const char*".
  • +
  • Change Linux Makefiles to allow external values for CFLAGS and LDFLAGS.
  • +
  • Change all destructors to virtual.
  • +
  • Fix crash when --break-blocks is used and there is no closing bracket.
  • +
  • Fix deleting the previous line when a closing bracket follows a comment close.
  • +
  • Fix not recognizing text in quotes when identifying struct access modifiers.
  • +
  • Fix not popping the paren stack when a bracket precedes an end of line comment.
  • +
  • Fix not breaking a closing bracket when empty parens are enclosed in a single line block.
  • +
  • Fix indenting of C# anonymous statement + closing bracket.
  • +
  • Fix recognition of C# non in-statement arrays.
  • +
  • Fix breaking single line blocks for C# abstract methods.
  • +
  • Fix not always clearing isNonInStatementArray flag.
  • +
  • Fix indenting "case" statements in a preprocessor definition when --indent-preprocessor is not requested.
  • +
  • Fix not recognizing the "volatile" type qualifier as a keyword.
  • +
  • Fix class initializers not being recognized as an in-statement indent.
  • +
  • Fix indenting Java abstract methods when "new" starts the line and brackets are broken.
  • +
  • Fix broken initializer lines (ending with comma) when there is more than one space after the type.
  • +
  • Fix --brackets=attach inserting a bracket inside comments following a preprocessor statement.
  • +
  • Fix --brackets=attach attaching an array bracket from a one line block to the previous line.
  • +
  • Fix --brackets=horstmann not breaking a comment line when the comment ends the line with a bracket.
  • +
  • Fix --pad-oper to recognize all * and & operators within a function call.
  • +
  • Fix --unpad-paren to recognize * and & operators within a function call.
  • +
  • Fix --pad-paren used with --delete-empty-lines causing a space to be added at end of line in some cases.
  • +
  • Fix --pad-paren padding a closing paren followed by a block paren.
  • +
  • Fix --add-brackets when a header is followed by a semi-colon.
  • +
  • Fix --align-pointer to pad or unpad pointers followed by parens or comments.
  • +
  • Fix --align-pointer to pad or unpad pointers following a scope resolution operator.
  • +
  • Fix --align-pointer to pad or unpad pointers that end the line.
  • +
  • Fix --align-pointer used with --pad-parens-out causing a space to be padded for each run.
  • +
  • Fix --break-blocks used with --delete-empty-lines causing an assert error when end of file is reached.
  • +
  • Fix --break-blocks used with --delete-empty-lines causing an assert error for some combinations of comment + lines.
  • +
  • Fix --break-blocks used with --delete-empty-lines causing a duplicate line in some cases.
  • +
  • Fix --break-blocks used with --delete-empty-lines not always breaking opening blocks.
  • +
  • Fix --break-blocks used with --delete-empty-lines not always deleting empty lines for closing blocks.
  • +
  • Fix --break-blocks used with --fill-empty-lines not always correctly filling empty lines in a switch statement.
  • -
  • Add new style --style=horstmann (-A9) using horstmann brackets to predefined styles.
  • -
  • Add new option ‑‑add-brackets (-j) and --add-one-line-brackets (-J) to place brackets around one line statements. -
  • -
  • Add new style --style=1tbs and --style=otbs (-A10) using linux brackets and the --add-brackets option to predefined - styles.
  • -
  • Add new option ‑‑pad‑header (‑H) from Mario Gleichmann to insert space padding after paren - headers.
  • -
  • Add new option ‑‑align‑pointer=type (-k1), ‑‑align‑pointer=middle (-k2) and - ‑‑align‑pointer=name (-k3) from J P Nurmi.
  • -
  • Add new option ‑‑lineend=windows (-z1), ‑‑lineend=linux (-z2) and ‑‑lineend=macold - (-z3) from MrTact.
  • -
  • Add new option ‑‑indent‑col1‑comments (-Y) to indent C++ comments beginning in column - one.
  • -
  • Add formatting of embedded SQL statements in C/C++.
  • -
  • Add rejecting 16 or 32 bit file encoding and display a warning message.
  • -
  • Remove .tmp file by using ostringstream instead of ofstream.  
  • -
  • Remove depreciated option style=kr.
  • -
  • Remove trace file from ASFormatter and use 'cout' instead.
  • -
  • Improve assembler statement processing to include extended assembly.
  • -
  • Improve assembler statement processing to include Microsoft specific lines and blocks.
  • -
  • Improve recognition of pointers and references vs. arithmetic operators.
  • -
  • Improve recognition of arithmetic operators for --pad-oper (-p) option.
  • -
  • Change "class" initializer statement to one indent.
  • -
  • Change "class" initializer statement continuation lines to align on the first initializer.
  • -
  • Change predefined styles to allow changes to spaces per indent.
  • -
  • Change --style=stroustroup to 5 spaces per indent.
  • -
  • Change --style=linux default minimum conditional indent to 4.
  • -
  • Change default formatting to leave paren headers unchanged instead of inserting space padding. -
  • -
  • Change ‑‑unpad‑paren to unpad headers unless padding is requested.
  • -
  • Change NONE_MODE brackets to allow run-in statements from horstmann type brackets.
  • -
  • Change array brackets to allow run-in statements from horstmann type brackets.
  • -
  • Change --min-conditional-indent to allow for statements preceded by a bracket (horstmann brackets).
  • -
  • Change ASBeautifier and ASFormatter to output an entire comment line instead of characters.
  • -
  • Change quote formatting in ASFormatter to output the entire string instead of single characters.
  • -
  • Change from Ettl Martin for cppcheck compliance.
  • -
  • Change space padding of line end comments to one space when the proper alignment cannot be maintained.
  • -
  • Change spaces per tab minimum value from 1 to 2.
  • -
  • Change the help display of "Formatting Options" to "Formatting Options" and "Padding Options".
  • -
  • Fix MinGW file globing by moving the _CRT_glob variable outside the astyle namespace.
  • -
  • Fix default line end processing to always output consistent line ends.
  • -
  • Fix identification of pointer dereferences and address-of indicators.
  • -
  • Fix memory leaks by changing static vectors to static vector pointers so the object can be deleted.
  • -
  • Fix console build trying to use Unicode character set.
  • -
  • Fix stringEndsWith method when end is longer than the string.
  • -
  • Fix --exclude option rejecting a full file path.
  • -
  • Fix --verbose option when used with --quiet.
  • -
  • Fix --quiet option for excluded files and directories.
  • -
  • Fix --indent-classes for C++ structs containing access modifiers.
  • -
  • Fix formatting of variable types with multiple names.
  • -
  • Fix from Christian Stimming for alignment of << and >> operators.
  • -
  • Fix in-statement indent of "enum class".
  • -
  • Fix 'if' statement following an 'else' sometimes attaching to a comment.
  • -
  • Fix recognition of non-indent line comments in the first two lines of a source file.
  • -
  • Fix non-instatement array to recognize an empty bracket.
  • -
  • Fix indenting non-indent line comments in an event table or message map.
  • -
  • Fix to move comments when breaking one line blocks and -keep-one-line-statements is used.
  • -
  • Fix to recognize parens in template definitions.
  • -
  • Fix recognition of class initializer when class description contains multiple lines.
  • -
  • Fix from Colin D Bennett for 64-bit comparison.
  • -
  • Fix console error procedure to terminate on an error.
  • -
  • Fix 'return' statement for padding or not padding arithmetic operators.
  • -
  • Fix C# 'delegate' and 'unchecked' not being identified as keywords.
  • -
  • Fix occasional array formatting problem with one-line blocks when indent-brackets is used.
  • -
  • Fix to check for max-instatement-indent when the previous line ends with an opening paren.
  • -
  • Fix predefined style options to allow the use of --indent=tab (-t) and --indent=force-tab (-T) options.
  • -
  • Fix --in-statement indent to allow for non-indentation tabs in the line.
  • -
  • Fix formatting problems with non in-statement arrays.
  • -
  • Fix infinite loop when preprocessor #else is missing #if.
  • -
  • Fix Borland string compares to check for comparison past the end of string.
  • -
  • Fix ‑‑fill‑empty‑lines when ‑‑indent=force‑tab is also used.
  • -
  • Fix break-blocks formatting with preceding mixed comments and line comments.
  • -
  • Fix not breaking a closing bracket following a comment.
  • -
  • Fix attached brackets to not change empty brackets when both are on the same line.
  • -
  • Fix attached brackets sometimes deleting a previous comment line when the bracket cannot be attached.
  • -
  • Fix attached brackets attaching a closing header to a single line block.
  • -
  • Fix broken brackets breaking a single line block before a comment.
  • -
  • Fix 'extern' keyword using in-statement indents instead of tab indents.
  • -
  • Fix errno checking problem on old OpenVMS versions.
  • -
  • Fix deleting a space before a line end comment when attaching 'else' to a closing bracket.
  • -
  • Fix adding a space before a line end comment when the comment is preceded by a tab.
  • -
  • Fix to leave tab indentation on no-indent line comments.
  • -
  • Fix comments when a bracket is added or removed from a line.
  • -
  • Fix indenting preprocessor statements in a wxWidgets or MFC macro.
  • -
  • Fix memory leak reporting of global and static class member vectors.
  • -
  • Refactor to implement unit testing and improve design and decomposition: -
      -
    • Replace multiple line conditional statements with a method to eliminate complex "not" (!) logic.
    • -
    • Change to call standardizePath when a vector entry is built.
    • -
    • Change g_console from an object to an object pointer to allow rebuilding the object.
    • -
    • Change ASConsole variables to private with getters and setters.
    • -
    • Change processOptions method to return to main instead of exiting.
    • -
    • Move formatFile call from getFilePaths to main.
    • -
    • Move peekNextChar function from ASBeautifier to ASBase.
    • -
    • Move multi-line comment alignment from ASBeautifier to ASFormatter.
    • -
    • Encapsulate global variable isModeManuallySet.
    • -
    • Extract methods formatOpeningBracket, formatClosingBracket and isCurrentBracketBroken.
    • -
    • Extract methods formatCommentOpener and formatCommentBody.
    • -
    • Extract methods formatLineCommentOpener and formatLineCommentBody.
    • -
    • Extract methods formatQuoteOpener and formatQuoteBody.
    • -
    • Extract methods processFiles and writeOutputFile.
    • -
    • Extract methods processSwitchBlock and findCaseColon.
    • -
    • Extract method updateExcludeVector.
    • -
    • Extract method copyTempStacks.
    • -
    • Extract method formatCinToCout.
    • -
    • Extract method isLineBreakBeforeClosingHeader.
    • -
    -
  • -
- -

- Artistic Style 1.23  (February 2009)

- -
    -
  • Add --brackets=stroustrup (-u) to bracket types.
  • -
  • Add --style=stroustrup to predefined styles.
  • -
  • Add --style=whitesmith to predefined styles.
  • -
  • Add --style=banner to predefined styles.
  • -
  • Add --style=k&r and --style=k/r to predefined styles.
  • -
  • Add --style=allman and --style=bsd to predefined styles.
  • -
  • Change --style=kr to --style=java.
  • -
  • Add short options -A1 thru -A8 for predefined styles.
  • -
  • Change the following long options to eliminate duplicate keys (the short options have not changed). -
      -
    • --force-indent=tab=# changed to --indent=force-tab=#
    • -
    • --brackets=break-closing changed to --break-closing-brackets
    • -
    • --pad=oper changed to --pad-oper
    • -
    • --pad=paren changed to --pad-paren
    • -
    • --pad=paren-out changed to --pad-paren-out
    • -
    • --pad=paren-out changed to --pad-paren-in
    • -
    • --unpad=paren changed to --unpad-paren
    • -
    • --one-line=keep-statement changed to --keep-one-line-statements
    • -
    • --one-line=keep-blocks changed to --keep-one-line-blocks
    • -
    -
  • -
  • Add new option --indent=force-tab (assumes tab setting is 4).
  • -
  • Add new option --delete‑empty‑lines to delete the empty lines within a function.
  • -
  • Add new option --formatted (-Q) to display only the files that are formatted.
  • -
  • Change --convert-tabs to replace tabs with spaces and maintain the correct spacing.
  • -
  • Change --indent-blocks to indent only blocks within a function.
  • -
  • Change --indent-blocks to NOT indent the opening bracket for namespaces, classes, and interfaces.
  • -
  • Change --indent-blocks and --indent-brackets to NOT indent namespaces unless --indent-namespaces is used.
  • -
  • Change --indent-blocks and --indent-brackets to always break closing headers so the 'else' aligns with the corresponding - 'if'.
  • -
  • Change --indent-blocks and --indent-brackets to be mutually exclusive (--indent‑blocks will be used). -
  • -
  • Fix --indent-blocks indenting a java 'interface' statement. 
  • -
  • Fix --indent-blocks to indenting opening brackets in a java method containing a 'throws' clause.
  • -
  • Fix --indent-blocks indenting opening brackets in a java static constructor.
  • -
  • Fix --indent-blocks formatting in a C++ const function.
  • -
  • Fix --indent‑brackets indenting brackets within comments.
  • -
  • Move set-up of predefined styles to ASFormatter so the style options will override all other options.
  • -
  • Fix --else-if statements to join by default.
  • -
  • Fix to always space pad after semi‑colons.
  • -
  • Fix --pad-oper to space pad all commas.
  • -
  • Fix --break‑blocks and --break‑blocks=all options. -
      -
    • Fix to recognize a semi‑colon as end of block when brackets are not used.
    • -
    • Fix to break comments preceding a block so that comments are kept with the block.
    • -
    • Fix 'for' statement semi‑colons being mistaken for the end of a statement.
    • -
    • Fix bracketFormatMode of  NONE_MODE to break closing headers.
    • -
    • Fix incorrect breaking of a block that follows a comment.
    • -
    • Fix breaking of opening and closing headers preceded by a comment.
    • -
    • Fix breaking of statements when comments follow a header block.
    • -
    • Fix incorrectly breaking blocks for namespaces, interfaces, and classes.
    • -
    • Fix incorrectly breaking blocks for access modifiers when keep-one-line-statements is used.
    • -
    • Fix to NOT break single line blocks.
    • -
    • Fix breaking a closing 'while' statement in a do-while block.
    • -
    • Fix preprocessor directives not resetting all variables.
    • -
    • Fix peekNextText function not correctly identifying an end of file condition.
    • -
    -
  • -
  • Add C# lambda expression arrow '=>' to list of operators so pad‑oper will not separate.
  • -
  • Add C# '??' to list of operators so pad‑oper will not separate.
  • -
  • Fix C# to identify 'add' and 'remove' methods as command type brackets.
  • -
  • Fix C# indentation of closing headers 'set' and 'remove'.
  • -
  • Fix C# to identify methods containing a 'where' keyword as block headers. 
  • -
  • Fix C# files to recognize preprocessor statements.
  • -
  • Fix C# indentation following a #region statement containing a keyword.
  • -
  • Fix C# to recognize nullable types so --pad‑paren will not separate (e.g. 'int?').
  • -
  • Fix C# to recognize non-generic default values (e.g. 'default(int)').
  • -
  • Fix C# indentation when a class declaration contains multiple class statements.
  • -
  • Fix C# linux bracket placement for an  interface statement.
  • -
  • Fix C# --break-elseifs also breaking 'catch' statements.
  • -
  • Fix C# --break-blocks breaking of 'set' and 'remove' statements.
  • -
  • Fix Java static constructor not being identified as a command type bracket.
  • -
  • Fix Java 'new' array not having an in statement indent.
  • -
  • Refactor NONE_MODE in ASFormatter to use common procedures with other bracket types.
  • -
  • Refactor astyle_main to improve maintainability. -
      -
    • New class ASConsole to encapsulate console variables.
    • -
    • New header file astyle_main.h
    • -
    • Move console only functions to ASConsole class.
    • -
    • New functions processOptions and processFilePath to improve decomposition.
    • -
    -
  • -
  • Apply patches from Eran Ifrah to remove memory leaks.
  • -
  • Apply patches from Max Horn for the unary plus operator.
  • -
  • Fix initialization of vector stack objects to remove memory leaks.
  • -
  • Add comma (,) to valid options separators in the options file.
  • -
  • Change to display all (instead of one) --exclude errors before abort.
  • -
  • Change astyle namespace to include all of astyle_main except the functions called externally.
  • -
  • Change licensing comments from LGPL version 2.1 to LGPL version 3.
  • -
  • Change JNI function call from GetVersion to AStyleGetVersion.
  • -
  • Remove 'extern' keyword from headers, nonParenHeaders, PreBlockStatements, and  PreCommandHeaders. -
  • -
  • Fix not always space padding a closing bracket.
  • -
  • Fix not space padding a closing header when breaking one line statements.
  • -
  • Fix --keep-one-line-blocks breaking closing headers on broken brackets.
  • -
  • Fix incorrectly attaching a bracket inside a comment after the end of a statement.
  • -
  • Add number of output lines processed to the --verbose option display.
  • -
  • Remove trace file from ASEnhancer and use 'cout' instead.
  • -
  • Replace INIT_CONTAINER and DELETE_CONTAINER macros with template functions.
  • -
  • Replace IS_A macro with isBracketType function.
  • -
  • Add GCC extended operators '<?' and '>?' (min and max) to list of operators.
  • -
  • Fix indentation and breaking of lines in struct and class bit fields.
  • -
  • Fix indentation of struct definitions.
  • -
  • Add 'union' to preDefinitionHeaders.
  • -
  • Change preBlockStatements and preDefinitionHeaders to be dependent on file type.
  • -
  • Fix a single quote mark used as an apostrophe in preprocessor directives being processed as a quotation.
  • -
  • Fix linux bracket formatting in nested namespaces.  
  • -
  • Fix --pad‑paren‑in not converting a tab to spaces if convert‑tabs is requested.
  • -
  • Fix incorrectly breaking a closing bracket when a header is not present.
  • -
  • Fix inserting duplicate bracketTypeStack entries when preprocessor directives contain unmatched brackets.
  • -
  • Fix bracketFormatMode of  NONE_MODE to correctly break single line blocks. 
  • -
  • Fix --keep‑one‑line‑blocks breaking 'if' statements when --break‑elseifs is used.
  • -
  • Remove inefficiencies for speed improvement. -
      -
    • Reduce calls to frequently used functions by first checking for specific requirements.
    • -
    • New class ASBase to inline frequently used functions and eliminate duplication between classes.
    • -
    • Change ASEnhancer from inherited to embedded to eliminate scope resolution requirements.
    • -
    • Change ASFormatter to output words instead of characters.
    • -
    • Resequence operator vectors and add new findHeader and findOperator functions.
    • -
    -
  • -
  • Fix NONE_MODE brackets to break a statement on the same line as an opening broken bracket.
  • -
  • Add 'errno' message for file and directory errors in the Linux build.
  • -
  • Add error checking for file remove and rename procedure.
  • -
  • Fix Linux abort for file sizes over 2 GB.
  • -
  • Fix searching the entire directory when only one file is requested.
  • -
  • Change --preserve-date increment to 2 units for Visual Studio 2008.
  • -
- -

- Artistic Style 1.22  (April 2008)

- -
    -
  • New --recursive (-r, -R) option to recursively process sub directories.
  • -
  • New --exclude option to exclude files and sub directories from processing.
  • -
  • New --verbose (-v) option to display optional information, such as release number and statistical data.
  • -
  • New --quiet (-q) option to suppress all informational messages.
  • -
  • Change --version short option to -V.
  • -
  • Change --convert‑tabs short option to -c.
  • -
  • Change to NOT write a new or backup file if a file contents has not changed, 
  • -
  • Change console file input procedure to create a .tmp file and preserve the input file on a crash.
  • -
  • Add Java Native Interface (JNI) for developers.
  • -
  • New peekNextLine and peekReset functions in ASStreamIterator.
  • -
  • Change ASEnhancer static variables to class member variables and reset them in the init() function.
  • -
  • Patch from Jens Krinke to fix stack underrun when the number of closing brackets exceed opening brackets.
  • -
  • Fix stack underrun when the number of closing parens exceed opening parens.
  • -
  • Fix processing of C/C++ string literal continuation lines.
  • -
  • Patch from Emilio Guijarro to correct padding and formatting of C# 'foreach' statements.
  • -
  • Fix C# to correctly identify accessor calls as not being headers.
  • -
  • Fix C# accessors (get and set) to break when breaking single line blocks.
  • -
  • Modify template procedure to process C# generics.
  • -
  • Fix processing of C# verbatim string literals.
  • -
  • Fix indentation of C# methods containing 'base' or 'this' keywords.
  • -
  • Fix indentation of C# methods containing generics.
  • -
  • Fix indentation of C# enums containing a type.
  • -
  • Fix indentation of C# catch blocks when 'catch' is a non-paren header.
  • -
  • Fix C# breaking of linux style brackets for methods containing generics and methods containing accessors.
  • -
  • Allow @ as a C# identifier prefix.
  • -
  • Fix assert error on C# UTF-8 files when the byte-order mark (BOM) is not followed by a space or a comment.
  • -
  • Fix nested preprocessor formatting by adding waitingBeautifierStack, activeBeautifierStack, waitingBeautifierStackLengthStack, - and activeBeautifierStackLengthStack to the ASBeautifier copy constructor and class destructor.
  • -
  • Fix ASStreamIterator end of file procedure for ASTYLE_LIB option.
  • -
  • Add pragma statements for Intel compiler to disable specific warning messages.
  • -
  • Move line number accumulators from ASSourceIterator class to private in ASStreamIterator class.
  • -
  • Fix reset of ASFormatter isInPreprocessor flag when \ is followed by a blank line.
  • -
  • Fix cin, cout, and cerr continuation lines to be indented.
  • -
  • Fix indentation of inner classes that inherit a base class.
  • -
  • Add astyle_main.cpp function declarations to astyle_main.cpp.
  • -
  • Change global variable prefix from '_' to 'g_'.
  • -
  • Inline selected ASStreamIterator functions.
  • -
  • Fix brackets=attach from attaching a bracket to a preprocessor directive.
  • -
  • Fix brackets=attach and brackets=linux breaking in an array immediately after a preprocessor directive.
  • -
  • Modify Jack Handy's wildcmp() function to make Windows comparisons case insensitive.
  • -
  • Fix not indenting a bracket when an attached bracket is broken and the following line is a no-indent comment.
  • -
  • Add error message if 'options=' file cannot be opened.
  • -
  • Bypass colon enclosed in quotes when processing 'case' statements.
  • -
  • Fix brackets=none not always breaking a closing bracket when breaking single line blocks.
  • -
  • Fix padding of header words that are in a definition (array).
  • -
  • Fix indentation of line immediately after a case statement where the object is enclosed in parens.
  • -
  • Fix breaking of multiple case statements when the object is enclosed in parens.
  • -
  • Fix indentation when there is more than one case statement on a line.
  • -
  • Remove processing for shouldBreakLineAfterComments (no longer used).
  • -
  • Fix brackets=break not breaking if before a comment that is not at end of line.
  • -
  • Fix brackets=none not space padding before a bracket.
  • -
  • Fix brackets=break and brackets=none not breaking comments following a bracket.
  • -
  • Fix blank line not being trimmed if inside a comment.
  • -
  • Fix brackets=break incorrectly space padding a preceding preprocessor statement line.
  • -
  • Fix brackets=attach attaching two consecutive opening brackets before an end-of-line comment.
  • -
  • Fix break-blocks not inserting a blank line if a bracket preceding a comment was moved to the following line.
  • -
  • Add 'X' to selected ASEnhancer variables to prevent conflict with ASBeautifier.
  • -
  • Fix brackets=none not space padding after a closing bracket that precedes a closing header.
  • -
  • Change minimum indent edit from 2 spaces to 1 space.
  • -
  • Change to check for preprocessor definitions in C/C++ files only.
  • -
  • Fix padding of template definitions when pad=oper is used.
  • -
  • Fix comment formatting in nested preprocessor definitions.
  • -
  • Fix header dependencies and warning messages for Linux GCC 4.3.
  • -
  • Use file name from disk for output to maintain correct case in Windows.
  • -
  • Fix pad=operator padding a negative value in a case statement.
  • -
  • Fix incorrect identification of bracket type following a struct statement.
  • -
  • Fix indentation of blank lines outside of brackets when --fill‑empty‑lines is used with --indent‑blocks - or --indent‑brackets.
  • -
  • Fix ASFormatter not identifying comments in preprocessor directives.
  • -
  • Fix brackets=attach deleting a preceding blank line in array type brackets.
  • -
- -

- Artistic Style 1.21  (June 2007)

- -
    -
  • New function, formatArrayBrackets, to improve array formatting and indentation.
  • -
  • Attach brackets to lines with end-of-line comments.
  • -
  • Break brackets from lines with end-of-line comments without bringing the comments with them.
  • -
  • Move ASFormatter and ASBeautifier static initialization from constructor to "init" function to allow for changes - in the file type.
  • -
  • Add --preserve-date (-Z) option.
  • -
  • New functions formatBrackets, padOperators and PadParens to improve decomposition.
  • -
  • Add identification of file mode (C, C#, or Java) to file open procedure.
  • -
  • Keywords in headers now depend on file mode (C, C#, or Java) and object type (formatter or beautifier).
  • -
  • Remove short options -c (mode=c) and -j (mode=java) since the mode is now set automatically from the file extension.
  • -
  • Change Linux bracket formatting for header files.
  • -
  • Fix formatting of empty blocks.
  • -
  • Expand BracketType definition.
  • -
  • Fix "do not change" bracket mode inconsistencies with other bracket formatting.
  • -
  • Remove mode=java from Java predefined style.
  • -
  • Change long option --errors-to-standard-output to --errors-to-stdout.
  • -
  • Fix breaking of struct variable declaration.
  • -
  • Add support for OpenVMS compiler.
  • -
  • Inline the ASBeautifier function isLegalNameChar.
  • -
  • Fix no-indent of block comments starting in column 1 or 2.
  • -
  • Fix formatting of Java anonymous class defined as a method call parameter (bracket within a paren).
  • -
  • Fix indentation for Java "for each" statement.
  • -
  • Fix bracket being attached to a preprocessor directive.
  • -
  • Fix extra indent of single line blocks when a previous line probation header is found.
  • -
  • Fix formatting of block comments when continuation lines have different leading whitespace characters.
  • -
  • Fix deleting a blank line before a bracket when brackets=attach.
  • -
  • Fix segmentation fault on preprocessor continuation line followed by an empty line.
  • -
  • Fix bad bracket indent that sometimes occurs when brackets=attach and it cannot be attached.
  • -
  • Fix trimming of comment lines.
  • -
  • Fix incorrect identification of "new" operator pointers as calculations.
  • -
  • Fix incorrect identification of assignments as command type bracket.
  • -
  • Fix incorrect indentation of pointers following a dot operator or pointer.
  • -
  • Fix attaching "else if" statements to a single line block.
  • -
  • Fix header recognition problem when header is proceeded by a tab instead of a space.
  • -
  • Fix line break when colon is followed by a comment.
  • -
  • Fix ASBeautifier not identifying a template definition.
  • -
  • Change indents around the end of line to two indents.
  • -
  • Change header includes to fix header dependencies for Linux GCC 4.3.
  • -
  • Add output line number for debugging.
  • -
  • Add filename to trace output.
  • -
  • Add trace for arrays.
  • -
  • Add trace for bracketType.
  • -
  • Fix no-indent comment in a #else preprocessor directive.
  • -
  • Fix block comment continuation line indent when block comments do not start the line.
  • -
  • Adjust position of block comments (/*) when padding is added or deleted.
  • -
  • Fix incorrect formatting if "return" is included in a function name.
  • -
  • Fix incorrect padding if template depth is greater that one and pad=oper is used.
  • -
  • Fix incorrect bracket type identification when bracket is followed by a comment.
  • -
  • Fix incorrect bracket type identification when a "const" method is declared.
  • -
  • Fix incorrect bracket type identification when pre-definition header is inside a paren.
  • -
  • Fix deleting a space when attaching a bracket with line comments.
  • -
  • Fix indentation when the conditional "?" operator is used in a single line statement.
  • -
  • Fix indentation when single line "if" statement is used.
  • -
  • Add pointers, multiply operators, and selected variables to do not unpad in paren unpad procedure.
  • -
  • Return exit code 0 for --version and --help.
  • -
- -

- Artistic Style 1.20.2  (February 2007)

- -
    -
  • Fix problems with the new stream I/O procedure added in release 1.20.1: -
      -
    • Fix adding an extra blank line at end of document.
    • -
    • Fix line ending on last line when cin and cout option is used.
    • -
    -
  • -
- -

- Artistic Style 1.20.1  (January 2007)

- -
    -
  • The following changes were made to improve processing for Mac OS X platforms: -
      -
    • Remove Makefile linker option -s and add a separate "strip" command.
    • -
    • Open console input and output streams as binary to allow Linux line ends on a Windows platform.
    • -
    • Change stream I/O procedure to allow for Mac OS 9 line endings.
    • -
    • Change output stream end of line from endl so output stream is not flushed with each write.
    • -
    • Change information messages from cerr to cout.
    • -
    • Removed messages when I/O is to cin and cout to accommodate TextWrangler.
    • -
    -
  • -
- -

- Artistic Style 1.20  (January 2007)

- -
    -
  • Call importOptions() from function AStyleMain() to allow slop in options parameters.
  • -
  • New makefiles for GCC and Intel with new compile options.
  • -
  • New project file for Visual C with new compile options.
  • -
  • Change comments to reflect the GNU Lesser General Public License.
  • -
  • Indent message maps for MFC and event tables for wxWidgets.
  • -
  • Fix incorrect formatting for an empty comment.
  • -
  • Fix "Unknown option" in default options file when last line does not contain CR or LF.
  • -
  • Patch from Dieter Bayer to fix case indent when a scope resolution operator is used.
  • -
  • Change long option --brackets=break-closing-headers to --brackets=break-closing.
  • -
  • Add short option -y for --brackets=break-closing.
  • -
  • Add short option -e for --break-elseifs.
  • -
  • Add short option -w for --indent-preprocessor.
  • -
  • Add short option -f for --break-blocks.
  • -
  • Add short option -F for --break-blocks=all.
  • -
  • Remove the backup file after formatting when --suffix=none.
  • -
  • Show total time at end of job.
  • -
  • Improved error handling for invalid options with ASTYLE_LIB.
  • -
  • Add function AStyleGetVersion() to ASTYLE_LIB option.
  • -
  • Change preprocessor macro from ASTYLE_GUI to ASTYLE_LIB.
  • -
  • Add astyle namespace to ASEnhancer.
  • -
  • Add #include <ctype.h> for Red Hat distribution of GCC 3.2 (prior to Jan 2004).
  • -
  • Remove commented-out code.
  • -
- -

- Artistic Style 1.19  (July 2006)

- -
    -
  • Add unpad=paren option.
  • -
  • Always pad paren headers (e.g. 'if', 'for', 'while').
  • -
  • Fix problem of pad=oper working different if pad=paren is declared.
  • -
  • Add additional tests to distinguish the multiplication operator from pointers.
  • -
  • Fix padding parens before a member access pointer (->).
  • -
  • If space padding has changed, move end-of-line comments to the original column, if possible.
  • -
  • Move potential calculation decision to outside of operator padding function.
  • -
  • Fix duplication of last line of source if a final endline is not present.
  • -
  • Fix class initializer not indented on last line if bracket is attached.
  • -
  • Fix identification of templates contained in parens.
  • -
  • Fix one line block occurring before end of class.
  • -
  • Fix line added after one line block with bracketFormatMode = NONE_MODE.
  • -
  • Add needed variables to ASBeautifier copy constructor.
  • -
  • Trim end of line for multi-line comments.
  • -
  • Add a breakLine before paren checks (needed for unpad=paren option).
  • -
  • Add trace file to ASFormatter.
  • -
  • Move formatting message from end to beginning of formatting.
  • -
  • Move the building of vectors to ASResource. Vectors for classes ASBeautifier and ASFormatter should now have the - same values.
  • -
  • Move debugging variable inLineNumber from ASFormatter to ASBeautifier.
  • -
  • Bypass char processing for UTF8 characters in ASBeautifier.
  • -
  • Move switchVariables struct from ASEnhancer to the header file.
  • -
  • Remove preprocessorHeader vector (not used).
  • -
  • Remove variable isInConst (not used).
  • -
  • Remove commented-out code.
  • -
- -

- Artistic Style 1.18  (June 2006)

- -
    -
  • The following changes were made for the option pad=oper: -
      -
    • Does not remove extra spaces from formatted expressions.
    • -
    • Does not pad opening parens on the outside.
    • -
    • Does not remove leading spaces from multi-line comments.
    • -
    • Does not pad negative numbers.
    • -
    • Does not add a space to the end of preprocessor directives.
    • -
    • Will not pad operators inside block parens [].
    • -
    -
  • -
  • The following changes were made for the option pad=paren: -
      -
    • Formats correctly with or without pad=oper.
    • -
    • Does not add a space for each additional run if pad=oper is not used.
    • -
    • Outside of opening paren is padded correctly.
    • -
    • Inside of closing paren is padded correctly.
    • -
    • Does not pad block parens [].
    • -
    • Added short option P, previously used for pad=all.
    • -
    -
  • -
  • Added new options pad=paren-out (d) and pad=paren-in (D).
  • -
  • Removed option pad=all.
  • -
  • Add short option V for convert-tabs.
  • -
  • Added bounds checking to options containing parameters.
  • -
  • Display a message when a default options file is used.
  • -
  • Replaced IS_PARAM_OPTION(S) macros with overloaded isParamOption. Fixed compare problem with short param options.
  • -
  • Fix EOF problem with default options file.
  • -
- -

- Artistic Style 1.17  (May 2006)

- -
    -
  • The following changes were made for processing bracketFormatMode = NONE_MODE: -
      -
    • Removed the function isFormattingEnabled() and always performed the formatting.
    • -
    • Removed the formatting bypass for NONE_MODE.
    • -
    • Fix brackets always being broken in the 2 cases where NONE_MODE formatting was done.
    • -
    • Added new functions to support the processing of NONE_MODE brackets.
    • -
    • Made other minor changes necessary for correct NONE_MODE processing.
    • -
    -
  • -
  • Changed indent cases option to indent the entire case block.
  • -
  • Changed to output Windows or Linux line endings.
  • -
  • Added ASEnhancer module for case statement indenting.
  • -
  • Correctederrorsinidentifyingoptionsindent=tab= ,andforce-indent=tab=.
  • -
  • Corrected errors in identifying options min-conditional-indent=, and max-instatement-indent=.
  • -
  • Improved error and information messages.
  • -
  • Added capability to compile as a console program, shared library, or static library.
  • -
  • Fixed problem with semicolons and parens being put on a line by themselves.
  • -
  • Fixed spaces being added before a line comment.
  • -
  • Fixed blank line added after some preprocessor statements.
  • -
  • Fixed preprocessor statements not being trimmed.
  • -
  • Do not indent line comments that begin in column 1 or 2.
  • -
  • Fixed indentation problem with ending }; of class statements.
  • -
  • Changed nextLine() function to eliminate char buffer limits.
  • -
  • Moved Windows default options file to %USERPROFILE%.
  • -
  • Removed NEW operators to prevent memory leaks.
  • -
  • Fixed space before the semicolon in return ; statement.
  • -
  • Fixed extra space that was sometimes added when pad operators was used.
  • -
  • Removed string parameter from IS_PARAM_OPTION.
  • -
  • Added forward declaration of parseOption() to eliminate compile error.
  • -
  • Added input line number counter for debugging.
  • -
  • Add statements to check for markers if break-blocks or break-blocks=all is used.
  • -
  • Remove warnings for signed/unsigned mismatch.
  • -
  • Removed COMPARE macro and used string compare.
  • -
  • Removed compiler_defines.h.
  • -
  • Removed USES_NAMESPACE declaration.
  • -
- -

- Artistic Style 1.16

- -
- There was no release 1.16. -
- -

- Artistic Style 1.15.3 (7 March 2002)

- -
    -
  • Bug fix in handling of brackets after line-comments.
  • -
  • Bug fix: C# add/remove event property headers now properly formatted.
  • -
- -

- Artistic Style 1.15.2 (2 March 2002)

- -
    -
  • Bug fixes in exception handling phrases, e.g. multiple catches and try..finally.
  • -
- -

- Artistic Style 1.15.1 (2 March 2002)

- -
    -
  • Bug fix: C# properties are now formatted properly.
  • -
- -

- Artistic Style 1.15.0 (2 March 2002)

- -
    -
  • Added support for C#.
  • -
  • Artistic Style is now licensed only under the GNU Public License (GPL).
  • -
  • Compilation under G++ 3.0 now works properly.
  • -
  • Bug fix: Opening brackets that appear at the beginning of a line immediately after an empty line comment are now - handled properly, and not appended as part of the line comment.
  • -
  • Bug fix: Brackets inside comments are now not mis-indented within the comment.
  • -
- -

- Artistic Style 1.14.1 (2 June 2001)

- -
    -
  • Bug fix: : '<' and '>' symbols within template declarations (e.g. 'foo<bar*, xoo>') are now left unpadded - in the padding modes.
  • -
  • Bug fix: Fixed false recognizing of headers within larger words (e.g. 'catch' in 'gcatch').
  • -
- -

- Artistic Style 1.14.0 (1 June 2001)

- -
    -
  • Bug fix: Fixed indentation of statements within preprocessor '#if...' statements.
  • -
  • Bug fix: Templates are now not broken from their bodies.
  • -
  • Bug fix: '<' and '>' symbols within template definitions (e.g. 'template<class T>') are now left unpadded - in the padding modes.
  • -
- -

- Artistic Style 1.13.8 (13 April 2001)

- -
    -
  • Bug fix: Fixed indentation of multiple nested non-block brackets, such as in multi bracketed static array declarations.
  • -
- -

- Artistic Style 1.13.7 (6 April 2001)

- -
    -
  • New option:'--force-indent=tab=#' (or 'T#') instructs astyle to indent using tabs in all the pre-statement white - space, including areas astyle's '--indent=tab' prefers to indent using spaces, such as white space in multi-line - statements.
  • -
  • Bug fix: Fixed unwanted empty line insertions between empty blocks (e.g. '{}') and closing brackets that come - immediately after them.
  • -
  • Bug fix: Fixed unwanted empty line insertions immediately after colons (e.g. 'default:', 'label:', ...)
  • -
- -

- Artistic Style 1.13.6 (24 January 2001)

- -
    -
  • Bug fix: Preprocessor lines now remain unpadded in padding modes.
  • -
- -

- Artistic Style 1.13.5 (24 January 2001)

- -
    -
  • Bug fix: Fixed the insertion of phantom empty lines immediately after {} blocks.
  • -
  • Bug fix: Bare open brackets ('{') with no preceding headers are now broken appropriately from their preceding - code lines in the 'attach' and 'linux' bracketmodes.
  • -
  • Bug fix: Fixed operator recognition for long operators such as '>>=', '<<= '.
  • -
- -

- Artistic Style 1.13.4 (24 January 2001)

- -
    -
  • Bug fix: L" unicode strings are now handled properly in padding modes.
  • -
  • Bug fix: Fixed the padding around '-' operators (which went sour somewhere in the past).
  • -
  • Bug fix: Fixed the handling of exponent numbers (e.g. 12.2e+2) in padding modes. The fix enables 'e+' to be regarded - as part of the exponent.
  • -
- -

- Artistic Style 1.13.3 (23 January 2001)

- -
    -
  • Line that contain both headers and their following non-header code (e.g. 'if (isFoo) doBar();') are now broken - by default into multiple lines. To keep these lines as single lines, use '--one-line= keep-statements'.
  • -
  • Added the new option '--break-elseifs' which breaks 'else if()' statements into multiple lines.
  • -
  • The option block breaking options now works properly with the padding options.
  • -
  • Various minor bug fixes.
  • -
- -

- Artistic Style 1.13.2 (21 January 2001)

- -
    -
  • Added the new option '--brackets=break-closing-headers'. When this option is added to either '--brackets=attach' - or '--brackets= linux', astyle breaks closing headers (e.g. 'else', 'catch') from their preceding closing brackets.
  • -
  • '--break-blocks' and '--break-blocks= all' now correctly handle blocks that appear immediately before closing - brackets, and do not append empty lines between them and the closing brackets.
  • -
- -

- Artistic Style 1.13.0 (27 September 1999)

- -
    -
  • Moved back to odd-minor-numbered development versions, and even-minor-numbered stable versions.
  • -
  • Added the new option '--break-blocks' which breaks apart unrelated blocks, labels, classes, etc.
  • -
  • Added the new option '--break-blocks=all' which also breaks apart blocks of closing headers, such as 'else', 'catch', - etc.
  • -
  • Fixed indentation handling of labels and class-definition identifiers such as 'public:', 'protected:', ... (thanks - to Daryn Adler for his patch)
  • -
  • Fixed indentation of nested class definitions. (thanks to Daryn Adler for his patch)
  • -
  • Added the new option '--indent-preprocessor' which (surprisingly) tries to reindent C/C++ preprocessor macro lines. - Astyle should do an pretty nice indentation job if the macro code is sane, but don't expect miracles for horrid - macro definitions...
  • -
- -

- Artistic Style 1.11.6 (27 September 1999)

- -
    -
  • Improved indentation of lines containing single-line blocks.
  • -
- -

- Artistic Style 1.11.5 (25 September 1999)

- -
    -
  • Improved the bug fix for a 'const' keyword bug which resulted in wrong indentation of methods that are declared - const.
  • -
- -

- Artistic Style 1.11.4 (18 September 1999)

- -
    -
  • Improved handling of single colons (':') in class headers, e.g. class Foo : public Bar { ... }
  • -
  • Improved handling of single colons (':') in method (constructor) headers, e.g. Foo::Foo(int a) : Bar(a)
  • -
- -

- Artistic Style 1.11.3 (16 September 1999)

- -
    -
  • Fixed a serious bug in the formatting of brackets, introduced in 1.11.2.
  • -
- -

- Artistic Style 1.11.2 (10 September 1999)

- -
    -
  • Fixed an indentation bug in statements that contain the 'const', that resulted in wrong indentation of array blocks - that where declared const. (Thanks Daniel!)
  • -
  • Fixed an indentation bug that could arise in lines that appear immediately after several preprocessor commands. - (Thanks Daniel!).
  • -
  • Fixed a bug that inserted an empty line after closing brackets if a comment appeared immediately prior to the - closing bracket. (Thanks Ed!)
  • -
  • Fixed a bug that eliminated empty lines between closing brackets and immediately following opening brackets. (Thanks - Ed!)
  • -
- -

- Artistic Style 1.11.1 (3 September 1999)

- -
    -
  • Fixed a bug that inserted an empty line at the begining of source files.
  • -
- -

- Artistic Style 1.11.0 (3 September 1999)

- -
    -
  • Astyle now filters out line-feeds ('\r') before begining to parse lines. This should take care of bizarre formatting - that existed when moving source files from Windows (which breaks lines with a linefeed AND newline ("\r\n") to - unix (which breaks lines only with newlines).
  • -
  • The "struct", "static" and "synchronized" keywords are now finally handled correctly in both the contexts of block - headers AND simple keywords.
  • -
  • Better treatment of precompiler lines that end with backslashes, and the lines that immediately follow them.
  • -
  • The '--indent-classes' (or '-C') option now works correctly (again...).
  • -
  • Series of short command-line options (e.g. "-b -s4 -C") are now parsed correctly.
  • -
- -

- Artistic Style 1.10.4  (27 July 1999)

- -
    -
  • Fixed a MAJOR bug (inserted in 1.10.3) that resulted wrong handling of double-colons ('::') in C++.
  • -
- -

- Artistic Style 1.10.3 (24 July 1999)

- -
    -
  • Fixed a bug (inserted yesterday) that resulted in unwanted line breaks before closing-brackets.
  • -
  • Fixed a bug in the handling of 'static' blocks in java.
  • -
  • Added the new option '--indent-cases' (or '-K') for indenting 'case XXX:' lines so they are flush with their following - code lines.
  • -
  • Added the new option '--fill-empty-lines' (or '-E') which fills empty lines with the white-space of their previous - line.
  • -
- -

- Artistic Style 1.10.2 (23 July 1999)

- -
    -
  • Fixed a series of related bugs that resulted in certain cases of lacking line breaks after close-brackets, and - colons. Thanks Jeroen!
  • -
- -

- Artistic Style 1.10.1 (18 July 1999)

- -
    -
  • Fixed a bug (introduced in astyle 1.10.0) that can result in missing line breaks before closing brackets if they - appear immediately after comments. Thanks Larry!
  • -
- -

- Artistic Style 1.10.0 Release (14 July 1999)

- -
    -
  • Improved handling of empty bracket blocks ( e.g.{ } ). Thanks Michael!
  • -
- -

- Artistic Style 1.10.0 Prerelease (4 July 1999)

- -
    -
  • Fixed a bug in the in-statement indentation algorithm which resulted in sub-optimal indentation of multiple-line - conditional statements that immediately follow headers such as 'if', 'else if', 'while', etc... As a result, the - current in-statement indentation is finally what it should have been long ago - MUCH better then in the last stable - versions.
  • -
  • The "linux" bracket style (in which definition brackets are broken while code brackets are attached) has been - fixed, and should finally work correctly.
  • -
  • Artistic Style can now parse both C/C++ and Java files in the same command. Unless a specific language mode is - specified (e.g. --style=java or --style=c), astyle will now automatically set the language mode according to each - file's suffix (java mode for the '.java' suffix , c mode otherwise).
  • -
  • Multiple statements in a single line (e.g. aaa; bbb; fff;) are now broken up by default.
  • -
  • Added the option '--one-line=keep-statements' (or '-o') that keeps multiple - statements in a single line attached, thus countering the default break detailed above.
  • -
  • Changed the option previously called '--keep-one-line-blocks' to '--one-line=keep-blocks', - for similarity with the new option above.
  • -
  • Changed the short option name of the option '--errors-to-standard-output' from '-o' - to '-X'.
  • -
  • Up to now, Artistic Style always inserted a minimal indent of twice the current selected indent - size inside multi-line conditional headers ('if', 'while' ...), so that it would be clear where the headers end - and the code after them begins. The current version adds the option '--min-conditional-indent=#' - (or '-m#') that sets the absolute minimal indent between conditional headers and their multiple-line - conditional statements. If this option is not specified, the default indent remains twice the current selected - indent size.
    For example, This option should come very handy in code that already has brackets - after EVERY conditional statement (even if just one line is in that bracket...) - in such a case, it would be - wise to set --min-conditional-indent=0 since the brackets already make it clear where the header - ends and the code begins...
  • -
  • Added the ability to set the assumed tab size when in '--indent-tab' mode by using '--indent-tab=#' - or '-t#' and replacing the # with the wanted size. If the size is not specified, - the size of each tab is assumed to be 4 spaces long.
  • -
- -

- Artistic Style 1.8.2 (18 March 1999)

- -
    -
  • Fixed pointer handling problems in ASBeautifier that led to crashes when parsing preprocessor commands.
  • -
  • Fixed the problem in locating the default options file in the directory pointed to by $HOME or %HOMEPATH% when - these system variables do not contain an '/' (or '\' ...) at their end.
  • -
  • Fixed inverse insertion of spaces vs. tabs when in -t mode. (Thanks Brian!)
  • -
  • Got rid of those pesky C4786 warnings when compiling under Visual C++ (Thanks John!)
  • -
- -

- Artistic Style 1.8.1 (9 March 1999)

- -
    -
  • Changed the '--style=k&r' option to '--style= kr' , so that linux/unix machines don't misinterpret the '&' - as a background processing command.
  • -
- -

- Artistic Style 1.8.0 (3 March 1999)

- -
    -
  • Added support for predefined styles. Current supported styles are: ansi, k&r, linux, gnu, java. - these can be set by using '--style=THESTYLE' (e.g. '--style=linux').
  • -
  • Added '--indent-blocks' (or -G) option, which adds indentation to entire blocks, including their - brackets, in similar fashion to the standard gnu style.
  • -
  • Added option '--brackets=linux' (or '-l') which breaks definition-block brackets, but attaches command-block - brackets.
  • -
  • Padding can now be set separately for operators alone('-p' or '--pad=oper'), parentheses alone ('--pad=paren) - or both ('-P' or '--pad=all').
  • -
  • Artistic Style looks for a default options file in the following order:
    1. The contents of the ARTISTIC_STYLE_OPTIONS - environment variable if it exists.
    2. The file called .astylerc in the directory pointed to by the HOME - environment variable ( i.e. $HOME/.astylerc ).
    3. The file called .astylerc in the directory - pointed to by the HOMEPATH environment variable ( i.e. %HOMEPATH%\.astylerc - ).
    If a default options file is found, the options in this file will be parsed BEFORE the command-line options. - Options within the default option file may be written without the preliminary '-' or '--'. Indentation within - #if , #else and #endif precompiler commands now works correctly even if the program lines between these precompiler - commands contain non-pared brackets.
  • -
  • Improved handling of labels (e.g. 'exit:'). By default, labels are now flushed completely to the left. Labels - can also be indented to one indent LESS than current standard indentation by using the new option '--indent-labels' - (or '-L') .
  • -
  • Fixed handling of the 'operator' keyword when it is preceded by a non space character (such as '&' or '*').
  • -
  • Fixed wrong bracket handling after 'throws' statements.
  • -
  • Fixed wrong indentation of single-line blocks. These where indented 1 indent to much.
  • -
  • Fixed wrong indentation of headers in internal classes (java mode). These where indented 1 indent to little.
  • -
  • The option ' --errors-to-standard-output' now has the one-letter option '-o'.
  • -
  • Fixed bug which resulted in an unneeded indent in function-declarations in which function-variables are declared - before the function declaration and are preceded by the 'static' keyword. Thanks Scott.
  • -
- -

- Artistic Style 1.6.0 (5 January 1999)

- -
    -
  • Fixed zero indentation that resulted when a '-suffix' option was set after a '--indent=spaces' (or '-s') option.
  • -
  • Wrong options are now announced.
  • -
  • Changed default indentation to NOT automatically indent class blocks and switch blocks. Instead, the new options - '--indent-classes' (or '-C') and '--indent-switches' (or '-S') should be used. The option '--indent-switches' - replaces the old option '--flush-switches'.
  • -
- -

- Artistic Style 1.4.1 (4 January 1999)

- -
    -
  • Fixed ability to write options without the preceding '--' in the default options file.
  • -
  • Added one-letter options to most options that had only long-options in version 1.4.0.
  • -
  • Added a '-v' or '--version' option that writes the current Artistic Style version.
  • -
- -

- Artistic Style 1.4.0 (3 January 1999)

- -
    -
  • MAJOR NEW CHANGE IN THE FORMAT OF OPTIONS:
    Options are now either short one-letter - options starting with '-', or long multi-letter options starting with '--'. The Short - one-letter options MAY BE ATTACHED TOGETHER. Thus, writing '-bps4' is the same as writing '-b -p -s4'.
    Many - options that have up to now had a 2 letter format now retain only their long format. I truly believe that the - combination of attached-one-letter options PLUS a default option's file containing long-letter-options related - to style will be much easier to work with than the previous setup.
  • -
  • Added support for a default options file (pointed to by the ARTISTIC_STYLE_OPTIONS environment - variable).
  • -
  • Changed downloading method from the server. From now, there will be specific directories containing the latest - stable sources, stable binaries, and development sources.
  • -
  • Space padding ('-p' or '--pad') now works correctly (1) around semicolons and commas, (2) between headers that - require parentheses after them (such as 'if', 'while'...)and those parentheses, and (3) after parentheses (unless - immediately followed by a ';' or ',' or '.').
  • -
  • From now on, namespace blocks are NOT indented by default. To indent namespace blocks use the new '--indent-namespaces' - option.
  • -
  • Added options '--errors-to-standard-output' for redirection of standard-error to standard-output from within Artistic - Style, and '--suffix=' for specifying a suffix other than '.orig' to append to original filenames.
  • -
  • Corrected indentation of 'default' in switch statements. (Up to now, this only worked correctly in java mode...).
  • -
- -

- Artistic Style 1.2.0 (19 December 1998)

- -
    -
  • Artistic Style 1.2.0 is the first stable result of a new version numbering, in which development versions are - numbered with an odd minor number (such as 1.1.x), and stable versions are numbered with an even number (1.2.x). - Thus, version 1.2.0 accumulates all the additions/changes of the 1.1.x development versions of Artistic Style.
  • -
  • A new '-ol' formatting mode that eliminates breaking of one-line blocks.
  • -
  • Fixed a SERIOUS bug, which resulted in wrong formatting of brackets ('{', '}') that came IMMEDIATELY AFTER definition - type brackets, (e.g. brackets that come right after 'class', 'interface', 'name-space', etc ...). This bug was - mistakenly introduced when I set out to correctly space-pad pointer and reference signs, somewhere in version - 0.9.x.
  • -
  • Fixed unwanted elimination of final empty lines.
  • -
  • Fixed broken indentation of virgin opening-brackets that occur immediately after a previous closing-bracket.
  • -
  • Fixed space-padding to not insert a space in front of ':' characters unless they are a part of a '? ... : ' statement.
  • -
- -

- Artistic Style 1.0.5  (11 December 1998)

- -
    -
  • 'extern' blocks now handled correctly.
  • -
  • Fixed handling of ^= in '-p' mode.
  • -
  • Win32 executables now contain wildcard expansion. *** Look at the README.TXT for info - on how to include wildcard expansion abilities when compiling Artistic Style under Win32. (Thanks for the info - on wildcard-expansion enabling, Nat!!!)
  • -
- -

- Artistic Style 1.0.4  (2 December 1998)

- -
    -
  • Fixed unwanted space-padding around urinary minuses and '-' symbols within exponents - (e.g. 2.5E-5) when using the '-p' option.
  • -
- -

- Artistic Style 1.0.3  (1 December 1998)

- -
    -
  • Control characters now remain in the indented file.
  • -
  • Fixed a bug in which long quoted white-space sequences where mistakenly eliminated - in the '-p' mode.
  • -
  • Fixed unwanted line-breaks in '-ab -p' mode, that in some cases occurred between '//' - and the rest of a line comment.
  • -
  • Fixed handling of '>>=', '<<= ' in '-p' mode.
  • -
- -

- Artistic Style 1.0.2 (27 November 1998)

- -
    -
  • Fixed a SERIOUS bug of missing needed line-breaks in lines immediately after line-comments - when in '-ab' mode.
  • -
  • Support for the 'finally' header.
  • -
  • lines that contain only white-space now become empty lines.
  • -
- -

- Artistic Style 1.0.1  (26 November 1998)

- -
    -
  • Fixed a SERIOUS bug, which lacked a needed line-break between closing brackets and - the headers that follow them (e.g. '} else') when in '-bb' mode. In fixing the bug, I used a variation on a patch - sent by Richard Bullington - THANKS!
  • -
  • Fixed a set of SERIOUS bugs which inserted an empty line into both the start and end - of the reindented file.
  • -
  • Improved documentation of formatting options in the file astyle.html .
  • -
- -

- Artistic Style 1.0.0 (24 November 1998)

- -
    -
  • Indented files now retain the original file name, while the original pre-indented - file is saved with a ".orig"at its end. Thus, after the call "astyle -bb foo.cpp", the newly indented file - will be called "foo.cpp", while a file called "foo.cpp.orig" will contain the original pre-indented - file.
  • -
  • Artistic Style may now be used and /or modified and/or distributed under EITHER - the "Artistic License", or the GNU General Public License (GPL).
  • -
  • Methods with headers that end with 'const' are now properly indented.
  • -
  • Cleaner, more robust, and better documented source code.
  • -
- -

- Artistic Style 0.9.2

- -
    -
  • Fixed a serious bug which led to a maximal supported source code line size of 128 - characters!!!
  • -
  • Maximal supported line size is now 1024 characters.
  • -
  • Fixed a serious bug in the handling of brackets inside '#define' statements.
  • -
  • Fixed a serious bug in which '#include' files containing slashes (i.e. #include <foo_dir/foo> ) where space-padded - when using option '-p' on C, C++ files.
  • -
- -

- Artistic Style 0.9.1

- -
    -
  • Much improved space-padding around pointers ('*') and references ('&') and the - 'operator' key-word in C and C++ source files when using the '-p' space padding option.
  • -
  • Fixed several pointer handling bugs which led to potential core dumps.
  • -
  • Version 0.9.1 now includes all the abilities I am planning for the final 1.0 version, and should be looked - at as the first pre-release version of Artistic Style.
  • -
- -

- Artistic Style 0.9.0

- -
    -
  • Added a formatting layer (ASFormatter.cpp) around the indentation layer (ASBeautifier.cpp).
  • -
  • As a result, the following formatting capabilities have been added: -
      -
    • Bracket ('{' and '}') placement in either ANSI C style or Java style.
    • -
    • Space padding around operators, i.e. (1+2)*3-4 becomes ( 1 + 2 ) * 3 - 4.
    • -
    -
  • -
  • Fixed the 'tab' elimination bug introduced in ASBeautifier 0.8.2.
  • -
  • Fixed a bug which under-indented class headers containing inheritance info.
  • -
- -

- ASBeautifier 0.8.2

- -
    -
  • Fixed indentation problem in brackets around 'struct', and 'union' blocks.
  • -
  • Added recognition for '\' characters in the end of lines.
  • -
  • Improved indentation of post-method-declaration variable initializations.
  • -
  • Several minor bug fixes.
  • -
- -

- ASBeautifier 0.8.1

- -
    -
  • Fixed an important bug in pointer arithmetic which resulted both in phantom indentation errors, and in core-dumps - when trying to indent java files.
  • -
- -

- ASBeautifier 0.8.0

- -
    -
  • This is the first public release of ASBeautifier. It is a direct port to C++ of JSBeautifier - 1.1.1, PLUS extensions to for C++ indentation.
  • -
  • So far, very little beta-testing has been done for the C++ extensions. This should - change extremely with the open-source release (this was the case with JSBeautifier...), so expect ASBeautifier - to become bug-free fast!!!
  • -
  • The C++ source code is not yet written in optimal quality. I rushed a little so that I could release this initial - release as soon as possible. This will soon change.
  • -
-

-  

- -
- - [SourceForge.net] -
- -

-  

+
  • Fix --unpad-paren used with --pad-paren-in not padding between opening parens when multiple parens are used.
  • +
  • Fix --pad-oper incorrectly padding a template with a default parameter.
  • +
  • Fix ASBeautifier findOperator() method to recognize a C# lambda (=>) operator.
  • +
  • Fix ASFormatter nextLine() method to output an entire operator instead of individual characters.
  • +
  • Fix incorrectly identifying '*' as pointers in block parens.
  • +
  • Fix MinGW -Wshadow warnings.
  • +
  • Fix VS2010 "string subscript out of range" asserts.
  • +
  • Refactor:
      +
    • Remove template definition for parseOptions() by using a vector reference instead of iterators as function arguments.
    • +
    • New ASOptions class to encapsulate global functions used by both the console and library builds.
    • +
    • Replace argc and argv in processOptions() with a vector to simplify test cases.
    • +
    • Replace IS_OPTION and IS_OPTIONS macros with ASOptions methods.
    • +
    • Replace GET_PARAM and GET_PARAMS macros with ASOptions methods.
    • +
    • Extract ASFormatter methods checkIfTemplateOpener() and isClosingHeader().
    • +
    + +

    + Artistic Style 1.24  (February 2010)

    + +
      +
    • Add new option ‑‑brackets=horstmann (-g) to place run‑in statements on the same line as an opening + bracket.
    • +
    • Add new style --style=horstmann (-A9) using horstmann brackets to predefined styles.
    • +
    • Add new option ‑‑add-brackets (-j) and --add-one-line-brackets (-J) to place brackets around one line + statements.
    • +
    • Add new style --style=1tbs and --style=otbs (-A10) using linux brackets and the --add-brackets option to predefined + styles.
    • +
    • Add new option ‑‑pad‑header (‑H) from Mario Gleichmann to insert space padding after paren + headers.
    • +
    • Add new option ‑‑align‑pointer=type (-k1), ‑‑align‑pointer=middle (-k2) and + ‑‑align‑pointer=name (-k3) from J P Nurmi.
    • +
    • Add new option ‑‑lineend=windows (-z1), ‑‑lineend=linux (-z2) and ‑‑lineend=macold + (-z3) from MrTact.
    • +
    • Add new option ‑‑indent‑col1‑comments (-Y) to indent C++ comments beginning in column + one.
    • +
    • Add formatting of embedded SQL statements in C/C++.
    • +
    • Add rejecting 16 or 32 bit file encoding and display a warning message.
    • +
    • Remove .tmp file by using ostringstream instead of ofstream.  
    • +
    • Remove depreciated option style=kr.
    • +
    • Remove trace file from ASFormatter and use 'cout' instead.
    • +
    • Improve assembler statement processing to include extended assembly.
    • +
    • Improve assembler statement processing to include Microsoft specific lines and blocks.
    • +
    • Improve recognition of pointers and references vs. arithmetic operators.
    • +
    • Improve recognition of arithmetic operators for --pad-oper (-p) option.
    • +
    • Change "class" initializer statement to one indent.
    • +
    • Change "class" initializer statement continuation lines to align on the first initializer.
    • +
    • Change predefined styles to allow changes to spaces per indent.
    • +
    • Change --style=stroustrup to 5 spaces per indent.
    • +
    • Change --style=linux default minimum conditional indent to 4.
    • +
    • Change default formatting to leave paren headers unchanged instead of inserting space padding.
    • +
    • Change ‑‑unpad‑paren to unpad headers unless padding is requested.
    • +
    • Change NONE_MODE brackets to allow run-in statements from horstmann type brackets.
    • +
    • Change array brackets to allow run-in statements from horstmann type brackets.
    • +
    • Change --min-conditional-indent to allow for statements preceded by a bracket (horstmann brackets).
    • +
    • Change ASBeautifier and ASFormatter to output an entire comment line instead of characters.
    • +
    • Change quote formatting in ASFormatter to output the entire string instead of single characters.
    • +
    • Change from Ettl Martin for cppcheck compliance.
    • +
    • Change space padding of line end comments to one space when the proper alignment cannot be maintained.
    • +
    • Change spaces per tab minimum value from 1 to 2.
    • +
    • Change the help display of "Formatting Options" to "Formatting Options" and "Padding Options".
    • +
    • Fix MinGW file globing by moving the _CRT_glob variable outside the astyle namespace.
    • +
    • Fix default line end processing to always output consistent line ends.
    • +
    • Fix identification of pointer dereferences and address-of indicators.
    • +
    • Fix memory leaks by changing static vectors to static vector pointers so the object can be deleted.
    • +
    • Fix console build trying to use Unicode character set.
    • +
    • Fix stringEndsWith method when end is longer than the string.
    • +
    • Fix --exclude option rejecting a full file path.
    • +
    • Fix --verbose option when used with --quiet.
    • +
    • Fix --quiet option for excluded files and directories.
    • +
    • Fix --indent-classes for C++ structs containing access modifiers.
    • +
    • Fix formatting of variable types with multiple names.
    • +
    • Fix from Christian Stimming for alignment of << and >> operators.
    • +
    • Fix in-statement indent of "enum class".
    • +
    • Fix 'if' statement following an 'else' sometimes attaching to a comment.
    • +
    • Fix recognition of non-indent line comments in the first two lines of a source file.
    • +
    • Fix non-instatement array to recognize an empty bracket.
    • +
    • Fix indenting non-indent line comments in an event table or message map.
    • +
    • Fix to move comments when breaking one line blocks and -keep-one-line-statements is used.
    • +
    • Fix to recognize parens in template definitions.
    • +
    • Fix recognition of class initializer when class description contains multiple lines.
    • +
    • Fix from Colin D Bennett for 64-bit comparison.
    • +
    • Fix console error procedure to terminate on an error.
    • +
    • Fix 'return' statement for padding or not padding arithmetic operators.
    • +
    • Fix C# 'delegate' and 'unchecked' not being identified as keywords.
    • +
    • Fix occasional array formatting problem with one-line blocks when indent-brackets is used.
    • +
    • Fix to check for max-instatement-indent when the previous line ends with an opening paren.
    • +
    • Fix predefined style options to allow the use of --indent=tab (-t) and --indent=force-tab (-T) options.
    • +
    • Fix --in-statement indent to allow for non-indentation tabs in the line.
    • +
    • Fix formatting problems with non in-statement arrays.
    • +
    • Fix infinite loop when preprocessor #else is missing #if.
    • +
    • Fix Borland string compares to check for comparison past the end of string.
    • +
    • Fix ‑‑fill‑empty‑lines when ‑‑indent=force‑tab is also used.
    • +
    • Fix break-blocks formatting with preceding mixed comments and line comments.
    • +
    • Fix not breaking a closing bracket following a comment.
    • +
    • Fix attached brackets to not change empty brackets when both are on the same line.
    • +
    • Fix attached brackets sometimes deleting a previous comment line when the bracket cannot be attached.
    • +
    • Fix attached brackets attaching a closing header to a single line block.
    • +
    • Fix broken brackets breaking a single line block before a comment.
    • +
    • Fix 'extern' keyword using in-statement indents instead of tab indents.
    • +
    • Fix errno checking problem on old OpenVMS versions.
    • +
    • Fix deleting a space before a line end comment when attaching 'else' to a closing bracket.
    • +
    • Fix adding a space before a line end comment when the comment is preceded by a tab.
    • +
    • Fix to leave tab indentation on no-indent line comments.
    • +
    • Fix comments when a bracket is added or removed from a line.
    • +
    • Fix indenting preprocessor statements in a wxWidgets or MFC macro.
    • +
    • Fix memory leak reporting of global and static class member vectors.
    • +
    • Refactor to implement unit testing and improve design and decomposition: +
        +
      • Replace multiple line conditional statements with a method to eliminate complex "not" (!) logic.
      • +
      • Change to call standardizePath when a vector entry is built.
      • +
      • Change g_console from an object to an object pointer to allow rebuilding the object.
      • +
      • Change ASConsole variables to private with getters and setters.
      • +
      • Change processOptions method to return to main instead of exiting.
      • +
      • Move formatFile call from getFilePaths to main.
      • +
      • Move peekNextChar function from ASBeautifier to ASBase.
      • +
      • Move multi-line comment alignment from ASBeautifier to ASFormatter.
      • +
      • Encapsulate global variable isModeManuallySet.
      • +
      • Extract methods formatOpeningBracket, formatClosingBracket and isCurrentBracketBroken.
      • +
      • Extract methods formatCommentOpener and formatCommentBody.
      • +
      • Extract methods formatLineCommentOpener and formatLineCommentBody.
      • +
      • Extract methods formatQuoteOpener and formatQuoteBody.
      • +
      • Extract methods processFiles and writeOutputFile.
      • +
      • Extract methods processSwitchBlock and findCaseColon.
      • +
      • Extract method updateExcludeVector.
      • +
      • Extract method copyTempStacks.
      • +
      • Extract method formatCinToCout.
      • +
      • Extract method isLineBreakBeforeClosingHeader.
      • +
      +
    • +
    + +

    + Artistic Style 1.23  (February 2009)

    + +
      +
    • Add --brackets=stroustrup (-u) to bracket types.
    • +
    • Add --style=stroustrup to predefined styles.
    • +
    • Add --style=whitesmith to predefined styles.
    • +
    • Add --style=banner to predefined styles.
    • +
    • Add --style=k&r and --style=k/r to predefined styles.
    • +
    • Add --style=allman and --style=bsd to predefined styles.
    • +
    • Change --style=kr to --style=java.
    • +
    • Add short options -A1 thru -A8 for predefined styles.
    • +
    • Change the following long options to eliminate duplicate keys (the short options have not changed). +
        +
      • --force-indent=tab=# changed to --indent=force-tab=#
      • +
      • --brackets=break-closing changed to --break-closing-brackets
      • +
      • --pad=oper changed to --pad-oper
      • +
      • --pad=paren changed to --pad-paren
      • +
      • --pad=paren-out changed to --pad-paren-out
      • +
      • --pad=paren-out changed to --pad-paren-in
      • +
      • --unpad=paren changed to --unpad-paren
      • +
      • --one-line=keep-statement changed to --keep-one-line-statements
      • +
      • --one-line=keep-blocks changed to --keep-one-line-blocks
      • +
      +
    • +
    • Add new option --indent=force-tab (assumes tab setting is 4).
    • +
    • Add new option --delete‑empty‑lines to delete the empty lines within a function.
    • +
    • Add new option --formatted (-Q) to display only the files that are formatted.
    • +
    • Change --convert-tabs to replace tabs with spaces and maintain the correct spacing.
    • +
    • Change --indent-blocks to indent only blocks within a function.
    • +
    • Change --indent-blocks to NOT indent the opening bracket for namespaces, classes, and interfaces.
    • +
    • Change --indent-blocks and --indent-brackets to NOT indent namespaces unless --indent-namespaces is used.
    • +
    • Change --indent-blocks and --indent-brackets to always break closing headers so the 'else' aligns with the corresponding + 'if'.
    • +
    • Change --indent-blocks and --indent-brackets to be mutually exclusive (--indent‑blocks will be used).
    • +
    • Fix --indent-blocks indenting a java 'interface' statement. 
    • +
    • Fix --indent-blocks to indenting opening brackets in a java method containing a 'throws' clause.
    • +
    • Fix --indent-blocks indenting opening brackets in a java static constructor.
    • +
    • Fix --indent-blocks formatting in a C++ const function.
    • +
    • Fix --indent‑brackets indenting brackets within comments.
    • +
    • Move set-up of predefined styles to ASFormatter so the style options will override all other options.
    • +
    • Fix --else-if statements to join by default.
    • +
    • Fix to always space pad after semi‑colons.
    • +
    • Fix --pad-oper to space pad all commas.
    • +
    • Fix --break‑blocks and --break‑blocks=all options. +
        +
      • Fix to recognize a semi‑colon as end of block when brackets are not used.
      • +
      • Fix to break comments preceding a block so that comments are kept with the block.
      • +
      • Fix 'for' statement semi‑colons being mistaken for the end of a statement.
      • +
      • Fix bracketFormatMode of  NONE_MODE to break closing headers.
      • +
      • Fix incorrect breaking of a block that follows a comment.
      • +
      • Fix breaking of opening and closing headers preceded by a comment.
      • +
      • Fix breaking of statements when comments follow a header block.
      • +
      • Fix incorrectly breaking blocks for namespaces, interfaces, and classes.
      • +
      • Fix incorrectly breaking blocks for access modifiers when keep-one-line-statements is used.
      • +
      • Fix to NOT break single line blocks.
      • +
      • Fix breaking a closing 'while' statement in a do-while block.
      • +
      • Fix preprocessor directives not resetting all variables.
      • +
      • Fix peekNextText function not correctly identifying an end of file condition.
      • +
      +
    • +
    • Add C# lambda expression arrow '=>' to list of operators so pad‑oper will not separate.
    • +
    • Add C# '??' to list of operators so pad‑oper will not separate.
    • +
    • Fix C# to identify 'add' and 'remove' methods as command type brackets.
    • +
    • Fix C# indentation of closing headers 'set' and 'remove'.
    • +
    • Fix C# to identify methods containing a 'where' keyword as block headers. 
    • +
    • Fix C# files to recognize preprocessor statements.
    • +
    • Fix C# indentation following a #region statement containing a keyword.
    • +
    • Fix C# to recognize nullable types so --pad‑paren will not separate (e.g. 'int?').
    • +
    • Fix C# to recognize non-generic default values (e.g. 'default(int)').
    • +
    • Fix C# indentation when a class declaration contains multiple class statements.
    • +
    • Fix C# linux bracket placement for an  interface statement.
    • +
    • Fix C# --break-elseifs also breaking 'catch' statements.
    • +
    • Fix C# --break-blocks breaking of 'set' and 'remove' statements.
    • +
    • Fix Java static constructor not being identified as a command type bracket.
    • +
    • Fix Java 'new' array not having an in statement indent.
    • +
    • Refactor NONE_MODE in ASFormatter to use common procedures with other bracket types.
    • +
    • Refactor astyle_main to improve maintainability. +
        +
      • New class ASConsole to encapsulate console variables.
      • +
      • New header file astyle_main.h
      • +
      • Move console only functions to ASConsole class.
      • +
      • New functions processOptions and processFilePath to improve decomposition.
      • +
      +
    • +
    • Apply patches from Eran Ifrah to remove memory leaks.
    • +
    • Apply patches from Max Horn for the unary plus operator.
    • +
    • Fix initialization of vector stack objects to remove memory leaks.
    • +
    • Add comma (,) to valid options separators in the options file.
    • +
    • Change to display all (instead of one) --exclude errors before abort.
    • +
    • Change astyle namespace to include all of astyle_main except the functions called externally.
    • +
    • Change licensing comments from LGPL version 2.1 to LGPL version 3.
    • +
    • Change JNI function call from GetVersion to AStyleGetVersion.
    • +
    • Remove 'extern' keyword from headers, nonParenHeaders, PreBlockStatements, and  PreCommandHeaders. +
    • +
    • Fix not always space padding a closing bracket.
    • +
    • Fix not space padding a closing header when breaking one line statements.
    • +
    • Fix --keep-one-line-blocks breaking closing headers on broken brackets.
    • +
    • Fix incorrectly attaching a bracket inside a comment after the end of a statement.
    • +
    • Add number of output lines processed to the --verbose option display.
    • +
    • Remove trace file from ASEnhancer and use 'cout' instead.
    • +
    • Replace INIT_CONTAINER and DELETE_CONTAINER macros with template functions.
    • +
    • Replace IS_A macro with isBracketType function.
    • +
    • Add GCC extended operators '<?' and '>?' (min and max) to list of operators.
    • +
    • Fix indentation and breaking of lines in struct and class bit fields.
    • +
    • Fix indentation of struct definitions.
    • +
    • Add 'union' to preDefinitionHeaders.
    • +
    • Change preBlockStatements and preDefinitionHeaders to be dependent on file type.
    • +
    • Fix a single quote mark used as an apostrophe in preprocessor directives being processed as a quotation.
    • +
    • Fix linux bracket formatting in nested namespaces.  
    • +
    • Fix --pad‑paren‑in not converting a tab to spaces if convert‑tabs is requested.
    • +
    • Fix incorrectly breaking a closing bracket when a header is not present.
    • +
    • Fix inserting duplicate bracketTypeStack entries when preprocessor directives contain unmatched brackets.
    • +
    • Fix bracketFormatMode of  NONE_MODE to correctly break single line blocks. 
    • +
    • Fix --keep‑one‑line‑blocks breaking 'if' statements when --break‑elseifs is used.
    • +
    • Remove inefficiencies for speed improvement. +
        +
      • Reduce calls to frequently used functions by first checking for specific requirements.
      • +
      • New class ASBase to inline frequently used functions and eliminate duplication between classes.
      • +
      • Change ASEnhancer from inherited to embedded to eliminate scope resolution requirements.
      • +
      • Change ASFormatter to output words instead of characters.
      • +
      • Resequence operator vectors and add new findHeader and findOperator functions.
      • +
      +
    • +
    • Fix NONE_MODE brackets to break a statement on the same line as an opening broken bracket.
    • +
    • Add 'errno' message for file and directory errors in the Linux build.
    • +
    • Add error checking for file remove and rename procedure.
    • +
    • Fix Linux abort for file sizes over 2 GB.
    • +
    • Fix searching the entire directory when only one file is requested.
    • +
    • Change --preserve-date increment to 2 units for Visual Studio 2008.
    • +
    + +

    + Artistic Style 1.22  (April 2008)

    + +
      +
    • New --recursive (-r, -R) option to recursively process sub directories.
    • +
    • New --exclude option to exclude files and sub directories from processing.
    • +
    • New --verbose (-v) option to display optional information, such as release number and statistical data.
    • +
    • New --quiet (-q) option to suppress all informational messages.
    • +
    • Change --version short option to -V.
    • +
    • Change --convert‑tabs short option to -c.
    • +
    • Change to NOT write a new or backup file if a file contents has not changed, 
    • +
    • Change console file input procedure to create a .tmp file and preserve the input file on a crash.
    • +
    • Add Java Native Interface (JNI) for developers.
    • +
    • New peekNextLine and peekReset functions in ASStreamIterator.
    • +
    • Change ASEnhancer static variables to class member variables and reset them in the init() function.
    • +
    • Patch from Jens Krinke to fix stack underrun when the number of closing brackets exceed opening brackets.
    • +
    • Fix stack underrun when the number of closing parens exceed opening parens.
    • +
    • Fix processing of C/C++ string literal continuation lines.
    • +
    • Patch from Emilio Guijarro to correct padding and formatting of C# 'foreach' statements.
    • +
    • Fix C# to correctly identify accessor calls as not being headers.
    • +
    • Fix C# accessors (get and set) to break when breaking single line blocks.
    • +
    • Modify template procedure to process C# generics.
    • +
    • Fix processing of C# verbatim string literals.
    • +
    • Fix indentation of C# methods containing 'base' or 'this' keywords.
    • +
    • Fix indentation of C# methods containing generics.
    • +
    • Fix indentation of C# enums containing a type.
    • +
    • Fix indentation of C# catch blocks when 'catch' is a non-paren header.
    • +
    • Fix C# breaking of linux style brackets for methods containing generics and methods containing accessors.
    • +
    • Allow @ as a C# identifier prefix.
    • +
    • Fix assert error on C# UTF-8 files when the byte-order mark (BOM) is not followed by a space or a comment.
    • +
    • Fix nested preprocessor formatting by adding waitingBeautifierStack, activeBeautifierStack, waitingBeautifierStackLengthStack, + and activeBeautifierStackLengthStack to the ASBeautifier copy constructor and class destructor.
    • +
    • Fix ASStreamIterator end of file procedure for ASTYLE_LIB option.
    • +
    • Add pragma statements for Intel compiler to disable specific warning messages.
    • +
    • Move line number accumulators from ASSourceIterator class to private in ASStreamIterator class.
    • +
    • Fix reset of ASFormatter isInPreprocessor flag when \ is followed by a blank line.
    • +
    • Fix cin, cout, and cerr continuation lines to be indented.
    • +
    • Fix indentation of inner classes that inherit a base class.
    • +
    • Add astyle_main.cpp function declarations to astyle_main.cpp.
    • +
    • Change global variable prefix from '_' to 'g_'.
    • +
    • Inline selected ASStreamIterator functions.
    • +
    • Fix brackets=attach from attaching a bracket to a preprocessor directive.
    • +
    • Fix brackets=attach and brackets=linux breaking in an array immediately after a preprocessor directive.
    • +
    • Modify Jack Handy's wildcmp() function to make Windows comparisons case insensitive.
    • +
    • Fix not indenting a bracket when an attached bracket is broken and the following line is a no-indent comment.
    • +
    • Add error message if 'options=' file cannot be opened.
    • +
    • Bypass colon enclosed in quotes when processing 'case' statements.
    • +
    • Fix brackets=none not always breaking a closing bracket when breaking single line blocks.
    • +
    • Fix padding of header words that are in a definition (array).
    • +
    • Fix indentation of line immediately after a case statement where the object is enclosed in parens.
    • +
    • Fix breaking of multiple case statements when the object is enclosed in parens.
    • +
    • Fix indentation when there is more than one case statement on a line.
    • +
    • Remove processing for shouldBreakLineAfterComments (no longer used).
    • +
    • Fix brackets=break not breaking if before a comment that is not at end of line.
    • +
    • Fix brackets=none not space padding before a bracket.
    • +
    • Fix brackets=break and brackets=none not breaking comments following a bracket.
    • +
    • Fix blank line not being trimmed if inside a comment.
    • +
    • Fix brackets=break incorrectly space padding a preceding preprocessor statement line.
    • +
    • Fix brackets=attach attaching two consecutive opening brackets before an end-of-line comment.
    • +
    • Fix break-blocks not inserting a blank line if a bracket preceding a comment was moved to the following line.
    • +
    • Add 'X' to selected ASEnhancer variables to prevent conflict with ASBeautifier.
    • +
    • Fix brackets=none not space padding after a closing bracket that precedes a closing header.
    • +
    • Change minimum indent edit from 2 spaces to 1 space.
    • +
    • Change to check for preprocessor definitions in C/C++ files only.
    • +
    • Fix padding of template definitions when pad=oper is used.
    • +
    • Fix comment formatting in nested preprocessor definitions.
    • +
    • Fix header dependencies and warning messages for Linux GCC 4.3.
    • +
    • Use file name from disk for output to maintain correct case in Windows.
    • +
    • Fix pad=operator padding a negative value in a case statement.
    • +
    • Fix incorrect identification of bracket type following a struct statement.
    • +
    • Fix indentation of blank lines outside of brackets when --fill‑empty‑lines is used with --indent‑blocks + or --indent‑brackets.
    • +
    • Fix ASFormatter not identifying comments in preprocessor directives.
    • +
    • Fix brackets=attach deleting a preceding blank line in array type brackets.
    • +
    + +

    + Artistic Style 1.21  (June 2007)

    + +
      +
    • New function, formatArrayBrackets, to improve array formatting and indentation.
    • +
    • Attach brackets to lines with end-of-line comments.
    • +
    • Break brackets from lines with end-of-line comments without bringing the comments with them.
    • +
    • Move ASFormatter and ASBeautifier static initialization from constructor to "init" function to allow for changes + in the file type.
    • +
    • Add --preserve-date (-Z) option.
    • +
    • New functions formatBrackets, padOperators and PadParens to improve decomposition.
    • +
    • Add identification of file mode (C, C#, or Java) to file open procedure.
    • +
    • Keywords in headers now depend on file mode (C, C#, or Java) and object type (formatter or beautifier).
    • +
    • Remove short options -c (mode=c) and -j (mode=java) since the mode is now set automatically from the file extension.
    • +
    • Change Linux bracket formatting for header files.
    • +
    • Fix formatting of empty blocks.
    • +
    • Expand BracketType definition.
    • +
    • Fix "do not change" bracket mode inconsistencies with other bracket formatting.
    • +
    • Remove mode=java from Java predefined style.
    • +
    • Change long option --errors-to-standard-output to --errors-to-stdout.
    • +
    • Fix breaking of struct variable declaration.
    • +
    • Add support for OpenVMS compiler.
    • +
    • Inline the ASBeautifier function isLegalNameChar.
    • +
    • Fix no-indent of block comments starting in column 1 or 2.
    • +
    • Fix formatting of Java anonymous class defined as a method call parameter (bracket within a paren).
    • +
    • Fix indentation for Java "for each" statement.
    • +
    • Fix bracket being attached to a preprocessor directive.
    • +
    • Fix extra indent of single line blocks when a previous line probation header is found.
    • +
    • Fix formatting of block comments when continuation lines have different leading whitespace characters.
    • +
    • Fix deleting a blank line before a bracket when brackets=attach.
    • +
    • Fix segmentation fault on preprocessor continuation line followed by an empty line.
    • +
    • Fix bad bracket indent that sometimes occurs when brackets=attach and it cannot be attached.
    • +
    • Fix trimming of comment lines.
    • +
    • Fix incorrect identification of "new" operator pointers as calculations.
    • +
    • Fix incorrect identification of assignments as command type bracket.
    • +
    • Fix incorrect indentation of pointers following a dot operator or pointer.
    • +
    • Fix attaching "else if" statements to a single line block.
    • +
    • Fix header recognition problem when header is proceeded by a tab instead of a space.
    • +
    • Fix line break when colon is followed by a comment.
    • +
    • Fix ASBeautifier not identifying a template definition.
    • +
    • Change indents around the end of line to two indents.
    • +
    • Change header includes to fix header dependencies for Linux GCC 4.3.
    • +
    • Add output line number for debugging.
    • +
    • Add filename to trace output.
    • +
    • Add trace for arrays.
    • +
    • Add trace for bracketType.
    • +
    • Fix no-indent comment in a #else preprocessor directive.
    • +
    • Fix block comment continuation line indent when block comments do not start the line.
    • +
    • Adjust position of block comments (/*) when padding is added or deleted.
    • +
    • Fix incorrect formatting if "return" is included in a function name.
    • +
    • Fix incorrect padding if template depth is greater that one and pad=oper is used.
    • +
    • Fix incorrect bracket type identification when bracket is followed by a comment.
    • +
    • Fix incorrect bracket type identification when a "const" method is declared.
    • +
    • Fix incorrect bracket type identification when pre-definition header is inside a paren.
    • +
    • Fix deleting a space when attaching a bracket with line comments.
    • +
    • Fix indentation when the conditional "?" operator is used in a single line statement.
    • +
    • Fix indentation when single line "if" statement is used.
    • +
    • Add pointers, multiply operators, and selected variables to do not unpad in paren unpad procedure.
    • +
    • Return exit code 0 for --version and --help.
    • +
    + +

    + Artistic Style 1.20.2  (February 2007)

    + +
      +
    • Fix problems with the new stream I/O procedure added in release 1.20.1: +
        +
      • Fix adding an extra blank line at end of document.
      • +
      • Fix line ending on last line when cin and cout option is used.
      • +
      +
    • +
    + +

    + Artistic Style 1.20.1  (January 2007)

    + +
      +
    • The following changes were made to improve processing for Mac OS X platforms: +
        +
      • Remove Makefile linker option -s and add a separate "strip" command.
      • +
      • Open console input and output streams as binary to allow Linux line ends on a Windows platform.
      • +
      • Change stream I/O procedure to allow for Mac OS 9 line endings.
      • +
      • Change output stream end of line from endl so output stream is not flushed with each write.
      • +
      • Change information messages from cerr to cout.
      • +
      • Removed messages when I/O is to cin and cout to accommodate TextWrangler.
      • +
      +
    • +
    + +

    + Artistic Style 1.20  (January 2007)

    + +
      +
    • Call importOptions() from function AStyleMain() to allow slop in options parameters.
    • +
    • New makefiles for GCC and Intel with new compile options.
    • +
    • New project file for Visual C with new compile options.
    • +
    • Change comments to reflect the GNU Lesser General Public License.
    • +
    • Indent message maps for MFC and event tables for wxWidgets.
    • +
    • Fix incorrect formatting for an empty comment.
    • +
    • Fix "Unknown option" in default options file when last line does not contain CR or LF.
    • +
    • Patch from Dieter Bayer to fix case indent when a scope resolution operator is used.
    • +
    • Change long option --brackets=break-closing-headers to --brackets=break-closing.
    • +
    • Add short option -y for --brackets=break-closing.
    • +
    • Add short option -e for --break-elseifs.
    • +
    • Add short option -w for --indent-preprocessor.
    • +
    • Add short option -f for --break-blocks.
    • +
    • Add short option -F for --break-blocks=all.
    • +
    • Remove the backup file after formatting when --suffix=none.
    • +
    • Show total time at end of job.
    • +
    • Improved error handling for invalid options with ASTYLE_LIB.
    • +
    • Add function AStyleGetVersion() to ASTYLE_LIB option.
    • +
    • Change preprocessor macro from ASTYLE_GUI to ASTYLE_LIB.
    • +
    • Add astyle namespace to ASEnhancer.
    • +
    • Add #include <ctype.h> for Red Hat distribution of GCC 3.2 (prior to Jan 2004).
    • +
    • Remove commented-out code.
    • +
    + +

    + Artistic Style 1.19  (July 2006)

    + +
      +
    • Add unpad=paren option.
    • +
    • Always pad paren headers (e.g. 'if', 'for', 'while').
    • +
    • Fix problem of pad=oper working different if pad=paren is declared.
    • +
    • Add additional tests to distinguish the multiplication operator from pointers.
    • +
    • Fix padding parens before a member access pointer (->).
    • +
    • If space padding has changed, move end-of-line comments to the original column, if possible.
    • +
    • Move potential calculation decision to outside of operator padding function.
    • +
    • Fix duplication of last line of source if a final endline is not present.
    • +
    • Fix class initializer not indented on last line if bracket is attached.
    • +
    • Fix identification of templates contained in parens.
    • +
    • Fix one line block occurring before end of class.
    • +
    • Fix line added after one line block with bracketFormatMode = NONE_MODE.
    • +
    • Add needed variables to ASBeautifier copy constructor.
    • +
    • Trim end of line for multi-line comments.
    • +
    • Add a breakLine before paren checks (needed for unpad=paren option).
    • +
    • Add trace file to ASFormatter.
    • +
    • Move formatting message from end to beginning of formatting.
    • +
    • Move the building of vectors to ASResource. Vectors for classes ASBeautifier and ASFormatter should now have the + same values.
    • +
    • Move debugging variable inLineNumber from ASFormatter to ASBeautifier.
    • +
    • Bypass char processing for UTF8 characters in ASBeautifier.
    • +
    • Move switchVariables struct from ASEnhancer to the header file.
    • +
    • Remove preprocessorHeader vector (not used).
    • +
    • Remove variable isInConst (not used).
    • +
    • Remove commented-out code.
    • +
    + +

    + Artistic Style 1.18  (June 2006)

    + +
      +
    • The following changes were made for the option pad=oper: +
        +
      • Does not remove extra spaces from formatted expressions.
      • +
      • Does not pad opening parens on the outside.
      • +
      • Does not remove leading spaces from multi-line comments.
      • +
      • Does not pad negative numbers.
      • +
      • Does not add a space to the end of preprocessor directives.
      • +
      • Will not pad operators inside block parens [].
      • +
      +
    • +
    • The following changes were made for the option pad=paren: +
        +
      • Formats correctly with or without pad=oper.
      • +
      • Does not add a space for each additional run if pad=oper is not used.
      • +
      • Outside of opening paren is padded correctly.
      • +
      • Inside of closing paren is padded correctly.
      • +
      • Does not pad block parens [].
      • +
      • Added short option P, previously used for pad=all.
      • +
      +
    • +
    • Added new options pad=paren-out (d) and pad=paren-in (D).
    • +
    • Removed option pad=all.
    • +
    • Add short option V for convert-tabs.
    • +
    • Added bounds checking to options containing parameters.
    • +
    • Display a message when a default options file is used.
    • +
    • Replaced IS_PARAM_OPTION(S) macros with overloaded isParamOption. Fixed compare problem with short param options.
    • +
    • Fix EOF problem with default options file.
    • +
    + +

    + Artistic Style 1.17  (May 2006)

    + +
      +
    • The following changes were made for processing bracketFormatMode = NONE_MODE: +
        +
      • Removed the function isFormattingEnabled() and always performed the formatting.
      • +
      • Removed the formatting bypass for NONE_MODE.
      • +
      • Fix brackets always being broken in the 2 cases where NONE_MODE formatting was done.
      • +
      • Added new functions to support the processing of NONE_MODE brackets.
      • +
      • Made other minor changes necessary for correct NONE_MODE processing.
      • +
      +
    • +
    • Changed indent cases option to indent the entire case block.
    • +
    • Changed to output Windows or Linux line endings.
    • +
    • Added ASEnhancer module for case statement indenting.
    • +
    • Corrected errors in identifying options indent=tab=, and force-indent=tab=.
    • +
    • Corrected errors in identifying options min-conditional-indent=, and max-instatement-indent=.
    • +
    • Improved error and information messages.
    • +
    • Added capability to compile as a console program, shared library, or static library.
    • +
    • Fixed problem with semicolons and parens being put on a line by themselves.
    • +
    • Fixed spaces being added before a line comment.
    • +
    • Fixed blank line added after some preprocessor statements.
    • +
    • Fixed preprocessor statements not being trimmed.
    • +
    • Do not indent line comments that begin in column 1 or 2.
    • +
    • Fixed indentation problem with ending }; of class statements.
    • +
    • Changed nextLine() function to eliminate char buffer limits.
    • +
    • Moved Windows default options file to %USERPROFILE%.
    • +
    • Removed NEW operators to prevent memory leaks.
    • +
    • Fixed space before the semicolon in return ; statement.
    • +
    • Fixed extra space that was sometimes added when pad operators was used.
    • +
    • Removed string parameter from IS_PARAM_OPTION.
    • +
    • Added forward declaration of parseOption() to eliminate compile error.
    • +
    • Added input line number counter for debugging.
    • +
    • Add statements to check for markers if break-blocks or break-blocks=all is used.
    • +
    • Remove warnings for signed/unsigned mismatch.
    • +
    • Removed COMPARE macro and used string compare.
    • +
    • Removed compiler_defines.h.
    • +
    • Removed USES_NAMESPACE declaration.
    • +
    + +

    + Artistic Style 1.16

    + +
    + There was no release 1.16. +
    + +

    + Artistic Style 1.15.3 (7 March 2002)

    + +
      +
    • Bug fix in handling of brackets after line-comments.
    • +
    • Bug fix: C# add/remove event property headers now properly formatted.
    • +
    + +

    + Artistic Style 1.15.2 (2 March 2002)

    + +
      +
    • Bug fixes in exception handling phrases, e.g. multiple catches and try..finally.
    • +
    + +

    + Artistic Style 1.15.1 (2 March 2002)

    + +
      +
    • Bug fix: C# properties are now formatted properly.
    • +
    + +

    + Artistic Style 1.15.0 (2 March 2002)

    + +
      +
    • Added support for C#.
    • +
    • Artistic Style is now licensed only under the GNU Public License (GPL).
    • +
    • Compilation under G++ 3.0 now works properly.
    • +
    • Bug fix: Opening brackets that appear at the beginning of a line immediately after an empty line comment are now + handled properly, and not appended as part of the line comment.
    • +
    • Bug fix: Brackets inside comments are now not mis-indented within the comment.
    • +
    + +

    + Artistic Style 1.14.1 (2 June 2001)

    + +
      +
    • Bug fix: : '<' and '>' symbols within template declarations (e.g. 'foo<bar*, xoo>') are now left unpadded + in the padding modes.
    • +
    • Bug fix: Fixed false recognizing of headers within larger words (e.g. 'catch' in 'gcatch').
    • +
    + +

    + Artistic Style 1.14.0 (1 June 2001)

    + +
      +
    • Bug fix: Fixed indentation of statements within preprocessor '#if...' statements.
    • +
    • Bug fix: Templates are now not broken from their bodies.
    • +
    • Bug fix: '<' and '>' symbols within template definitions (e.g. 'template<class T>') are now left unpadded + in the padding modes.
    • +
    + +

    + Artistic Style 1.13.8 (13 April 2001)

    + +
      +
    • Bug fix: Fixed indentation of multiple nested non-block brackets, such as in multi bracketed static array declarations.
    • +
    + +

    + Artistic Style 1.13.7 (6 April 2001)

    + +
      +
    • New option:'--force-indent=tab=#' (or 'T#') instructs astyle to indent using tabs in all the pre-statement white + space, including areas astyle's '--indent=tab' prefers to indent using spaces, such as white space in multi-line + statements.
    • +
    • Bug fix: Fixed unwanted empty line insertions between empty blocks (e.g. '{}') and closing brackets that come + immediately after them.
    • +
    • Bug fix: Fixed unwanted empty line insertions immediately after colons (e.g. 'default:', 'label:', ...)
    • +
    + +

    + Artistic Style 1.13.6 (24 January 2001)

    + +
      +
    • Bug fix: Preprocessor lines now remain unpadded in padding modes.
    • +
    + +

    + Artistic Style 1.13.5 (24 January 2001)

    + +
      +
    • Bug fix: Fixed the insertion of phantom empty lines immediately after {} blocks.
    • +
    • Bug fix: Bare open brackets ('{') with no preceding headers are now broken appropriately from their preceding + code lines in the 'attach' and 'linux' bracketmodes.
    • +
    • Bug fix: Fixed operator recognition for long operators such as '>>=', '<<= '.
    • +
    + +

    + Artistic Style 1.13.4 (24 January 2001)

    + +
      +
    • Bug fix: L" unicode strings are now handled properly in padding modes.
    • +
    • Bug fix: Fixed the padding around '-' operators (which went sour somewhere in the past).
    • +
    • Bug fix: Fixed the handling of exponent numbers (e.g. 12.2e+2) in padding modes. The fix enables 'e+' to be regarded + as part of the exponent.
    • +
    + +

    + Artistic Style 1.13.3 (23 January 2001)

    + +
      +
    • Line that contain both headers and their following non-header code (e.g. 'if (isFoo) doBar();') are now broken + by default into multiple lines. To keep these lines as single lines, use '--one-line= keep-statements'.
    • +
    • Added the new option '--break-elseifs' which breaks 'else if()' statements into multiple lines.
    • +
    • The option block breaking options now works properly with the padding options.
    • +
    • Various minor bug fixes.
    • +
    + +

    + Artistic Style 1.13.2 (21 January 2001)

    + +
      +
    • Added the new option '--brackets=break-closing-headers'. When this option is added to either '--brackets=attach' + or '--brackets= linux', astyle breaks closing headers (e.g. 'else', 'catch') from their preceding closing brackets.
    • +
    • '--break-blocks' and '--break-blocks= all' now correctly handle blocks that appear immediately before closing + brackets, and do not append empty lines between them and the closing brackets.
    • +
    + +

    + Artistic Style 1.13.0 (27 September 1999)

    + +
      +
    • Moved back to odd-minor-numbered development versions, and even-minor-numbered stable versions.
    • +
    • Added the new option '--break-blocks' which breaks apart unrelated blocks, labels, classes, etc.
    • +
    • Added the new option '--break-blocks=all' which also breaks apart blocks of closing headers, such as 'else', 'catch', + etc.
    • +
    • Fixed indentation handling of labels and class-definition identifiers such as 'public:', 'protected:', ... (thanks + to Daryn Adler for his patch)
    • +
    • Fixed indentation of nested class definitions. (thanks to Daryn Adler for his patch)
    • +
    • Added the new option '--indent-preprocessor' which (surprisingly) tries to reindent C/C++ preprocessor macro lines. + Astyle should do an pretty nice indentation job if the macro code is sane, but don't expect miracles for horrid + macro definitions...
    • +
    + +

    + Artistic Style 1.11.6 (27 September 1999)

    + +
      +
    • Improved indentation of lines containing single-line blocks.
    • +
    + +

    + Artistic Style 1.11.5 (25 September 1999)

    + +
      +
    • Improved the bug fix for a 'const' keyword bug which resulted in wrong indentation of methods that are declared + const.
    • +
    + +

    + Artistic Style 1.11.4 (18 September 1999)

    + +
      +
    • Improved handling of single colons (':') in class headers, e.g. class Foo : public Bar { ... }
    • +
    • Improved handling of single colons (':') in method (constructor) headers, e.g. Foo::Foo(int a) : Bar(a)
    • +
    + +

    + Artistic Style 1.11.3 (16 September 1999)

    + +
      +
    • Fixed a serious bug in the formatting of brackets, introduced in 1.11.2.
    • +
    + +

    + Artistic Style 1.11.2 (10 September 1999)

    + +
      +
    • Fixed an indentation bug in statements that contain the 'const', that resulted in wrong indentation of array blocks + that where declared const. (Thanks Daniel!)
    • +
    • Fixed an indentation bug that could arise in lines that appear immediately after several preprocessor commands. + (Thanks Daniel!).
    • +
    • Fixed a bug that inserted an empty line after closing brackets if a comment appeared immediately prior to the + closing bracket. (Thanks Ed!)
    • +
    • Fixed a bug that eliminated empty lines between closing brackets and immediately following opening brackets. (Thanks + Ed!)
    • +
    + +

    + Artistic Style 1.11.1 (3 September 1999)

    + +
      +
    • Fixed a bug that inserted an empty line at the begining of source files.
    • +
    + +

    + Artistic Style 1.11.0 (3 September 1999)

    + +
      +
    • Astyle now filters out line-feeds ('\r') before begining to parse lines. This should take care of bizarre formatting + that existed when moving source files from Windows (which breaks lines with a linefeed AND newline ("\r\n") to + unix (which breaks lines only with newlines).
    • +
    • The "struct", "static" and "synchronized" keywords are now finally handled correctly in both the contexts of block + headers AND simple keywords.
    • +
    • Better treatment of precompiler lines that end with backslashes, and the lines that immediately follow them.
    • +
    • The '--indent-classes' (or '-C') option now works correctly (again...).
    • +
    • Series of short command-line options (e.g. "-b -s4 -C") are now parsed correctly.
    • +
    + +

    + Artistic Style 1.10.4  (27 July 1999)

    + +
      +
    • Fixed a MAJOR bug (inserted in 1.10.3) that resulted wrong handling of double-colons ('::') in C++.
    • +
    + +

    + Artistic Style 1.10.3 (24 July 1999)

    + +
      +
    • Fixed a bug (inserted yesterday) that resulted in unwanted line breaks before closing-brackets.
    • +
    • Fixed a bug in the handling of 'static' blocks in java.
    • +
    • Added the new option '--indent-cases' (or '-K') for indenting 'case XXX:' lines so they are flush with their following + code lines.
    • +
    • Added the new option '--fill-empty-lines' (or '-E') which fills empty lines with the white-space of their previous + line.
    • +
    + +

    + Artistic Style 1.10.2 (23 July 1999)

    + +
      +
    • Fixed a series of related bugs that resulted in certain cases of lacking line breaks after close-brackets, and + colons. Thanks Jeroen!
    • +
    + +

    + Artistic Style 1.10.1 (18 July 1999)

    + +
      +
    • Fixed a bug (introduced in astyle 1.10.0) that can result in missing line breaks before closing brackets if they + appear immediately after comments. Thanks Larry!
    • +
    + +

    + Artistic Style 1.10.0 Release (14 July 1999)

    + +
      +
    • Improved handling of empty bracket blocks ( e.g.{ } ). Thanks Michael!
    • +
    + +

    + Artistic Style 1.10.0 Prerelease (4 July 1999)

    + +
      +
    • Fixed a bug in the in-statement indentation algorithm which resulted in sub-optimal indentation of multiple-line + conditional statements that immediately follow headers such as 'if', 'else if', 'while', etc... As a result, the + current in-statement indentation is finally what it should have been long ago - MUCH better then in the last stable + versions.
    • +
    • The "linux" bracket style (in which definition brackets are broken while code brackets are attached) has been + fixed, and should finally work correctly.
    • +
    • Artistic Style can now parse both C/C++ and Java files in the same command. Unless a specific language mode is + specified (e.g. --style=java or --style=c), astyle will now automatically set the language mode according to each + file's suffix (java mode for the '.java' suffix , c mode otherwise).
    • +
    • Multiple statements in a single line (e.g. aaa; bbb; fff;) are now broken up by default.
    • +
    • Added the option '--one-line=keep-statements' (or '-o') that keeps multiple + statements in a single line attached, thus countering the default break detailed above.
    • +
    • Changed the option previously called '--keep-one-line-blocks' to '--one-line=keep-blocks', + for similarity with the new option above.
    • +
    • Changed the short option name of the option '--errors-to-standard-output' from '-o' + to '-X'.
    • +
    • Up to now, Artistic Style always inserted a minimal indent of twice the current selected indent + size inside multi-line conditional headers ('if', 'while' ...), so that it would be clear where the headers end + and the code after them begins. The current version adds the option '--min-conditional-indent=#' + (or '-m#') that sets the absolute minimal indent between conditional headers and their multiple-line + conditional statements. If this option is not specified, the default indent remains twice the current selected + indent size.
      For example, This option should come very handy in code that already has brackets + after EVERY conditional statement (even if just one line is in that bracket...) - in such a case, it would be + wise to set --min-conditional-indent=0 since the brackets already make it clear where the header + ends and the code begins...
    • +
    • Added the ability to set the assumed tab size when in '--indent-tab' mode by using '--indent-tab=#' + or '-t#' and replacing the # with the wanted size. If the size is not specified, + the size of each tab is assumed to be 4 spaces long.
    • +
    + +

    + Artistic Style 1.8.2 (18 March 1999)

    + +
      +
    • Fixed pointer handling problems in ASBeautifier that led to crashes when parsing preprocessor commands.
    • +
    • Fixed the problem in locating the default options file in the directory pointed to by $HOME or %HOMEPATH% when + these system variables do not contain an '/' (or '\' ...) at their end.
    • +
    • Fixed inverse insertion of spaces vs. tabs when in -t mode. (Thanks Brian!)
    • +
    • Got rid of those pesky C4786 warnings when compiling under Visual C++ (Thanks John!)
    • +
    + +

    + Artistic Style 1.8.1 (9 March 1999)

    + +
      +
    • Changed the '--style=k&r' option to '--style= kr' , so that linux/unix machines don't misinterpret the '&' + as a background processing command.
    • +
    + +

    + Artistic Style 1.8.0 (3 March 1999)

    + +
      +
    • Added support for predefined styles. Current supported styles are: ansi, k&r, linux, gnu, java. + these can be set by using '--style=THESTYLE' (e.g. '--style=linux').
    • +
    • Added '--indent-blocks' (or -G) option, which adds indentation to entire blocks, including their + brackets, in similar fashion to the standard gnu style.
    • +
    • Added option '--brackets=linux' (or '-l') which breaks definition-block brackets, but attaches command-block + brackets.
    • +
    • Padding can now be set separately for operators alone('-p' or '--pad=oper'), parentheses alone ('--pad=paren) + or both ('-P' or '--pad=all').
    • +
    • Artistic Style looks for a default options file in the following order:
      1. The contents of the ARTISTIC_STYLE_OPTIONS + environment variable if it exists.
      2. The file called .astylerc in the directory pointed to by the HOME + environment variable ( i.e. $HOME/.astylerc ).
      3. The file called .astylerc in the directory + pointed to by the HOMEPATH environment variable ( i.e. %HOMEPATH%\.astylerc + ).
      If a default options file is found, the options in this file will be parsed BEFORE the command-line options. + Options within the default option file may be written without the preliminary '-' or '--'. Indentation within + #if , #else and #endif precompiler commands now works correctly even if the program lines between these precompiler + commands contain non-pared brackets.
    • +
    • Improved handling of labels (e.g. 'exit:'). By default, labels are now flushed completely to the left. Labels + can also be indented to one indent LESS than current standard indentation by using the new option '--indent-labels' + (or '-L') .
    • +
    • Fixed handling of the 'operator' keyword when it is preceded by a non space character (such as '&' or '*').
    • +
    • Fixed wrong bracket handling after 'throws' statements.
    • +
    • Fixed wrong indentation of single-line blocks. These where indented 1 indent to much.
    • +
    • Fixed wrong indentation of headers in internal classes (java mode). These where indented 1 indent to little.
    • +
    • The option ' --errors-to-standard-output' now has the one-letter option '-o'.
    • +
    • Fixed bug which resulted in an unneeded indent in function-declarations in which function-variables are declared + before the function declaration and are preceded by the 'static' keyword. Thanks Scott.
    • +
    + +

    + Artistic Style 1.6.0 (5 January 1999)

    + +
      +
    • Fixed zero indentation that resulted when a '-suffix' option was set after a '--indent=spaces' (or '-s') option.
    • +
    • Wrong options are now announced.
    • +
    • Changed default indentation to NOT automatically indent class blocks and switch blocks. Instead, the new options + '--indent-classes' (or '-C') and '--indent-switches' (or '-S') should be used. The option '--indent-switches' + replaces the old option '--flush-switches'.
    • +
    + +

    + Artistic Style 1.4.1 (4 January 1999)

    + +
      +
    • Fixed ability to write options without the preceding '--' in the default options file.
    • +
    • Added one-letter options to most options that had only long-options in version 1.4.0.
    • +
    • Added a '-v' or '--version' option that writes the current Artistic Style version.
    • +
    + +

    + Artistic Style 1.4.0 (3 January 1999)

    + +
      +
    • MAJOR NEW CHANGE IN THE FORMAT OF OPTIONS:
      Options are now either short one-letter + options starting with '-', or long multi-letter options starting with '--'. The Short + one-letter options MAY BE ATTACHED TOGETHER. Thus, writing '-bps4' is the same as writing '-b -p -s4'.
      Many + options that have up to now had a 2 letter format now retain only their long format. I truly believe that the + combination of attached-one-letter options PLUS a default option's file containing long-letter-options related + to style will be much easier to work with than the previous setup.
    • +
    • Added support for a default options file (pointed to by the ARTISTIC_STYLE_OPTIONS environment + variable).
    • +
    • Changed downloading method from the server. From now, there will be specific directories containing the latest + stable sources, stable binaries, and development sources.
    • +
    • Space padding ('-p' or '--pad') now works correctly (1) around semicolons and commas, (2) between headers that + require parentheses after them (such as 'if', 'while'...)and those parentheses, and (3) after parentheses (unless + immediately followed by a ';' or ',' or '.').
    • +
    • From now on, namespace blocks are NOT indented by default. To indent namespace blocks use the new '--indent-namespaces' + option.
    • +
    • Added options '--errors-to-standard-output' for redirection of standard-error to standard-output from within Artistic + Style, and '--suffix=' for specifying a suffix other than '.orig' to append to original filenames.
    • +
    • Corrected indentation of 'default' in switch statements. (Up to now, this only worked correctly in java mode...).
    • +
    + +

    + Artistic Style 1.2.0 (19 December 1998)

    + +
      +
    • Artistic Style 1.2.0 is the first stable result of a new version numbering, in which development versions are + numbered with an odd minor number (such as 1.1.x), and stable versions are numbered with an even number (1.2.x). + Thus, version 1.2.0 accumulates all the additions/changes of the 1.1.x development versions of Artistic Style.
    • +
    • A new '-ol' formatting mode that eliminates breaking of one-line blocks.
    • +
    • Fixed a SERIOUS bug, which resulted in wrong formatting of brackets ('{', '}') that came IMMEDIATELY AFTER definition + type brackets, (e.g. brackets that come right after 'class', 'interface', 'name-space', etc ...). This bug was + mistakenly introduced when I set out to correctly space-pad pointer and reference signs, somewhere in version + 0.9.x.
    • +
    • Fixed unwanted elimination of final empty lines.
    • +
    • Fixed broken indentation of virgin opening-brackets that occur immediately after a previous closing-bracket.
    • +
    • Fixed space-padding to not insert a space in front of ':' characters unless they are a part of a '? ... : ' statement.
    • +
    + +

    + Artistic Style 1.0.5  (11 December 1998)

    + +
      +
    • 'extern' blocks now handled correctly.
    • +
    • Fixed handling of ^= in '-p' mode.
    • +
    • Win32 executables now contain wildcard expansion. *** Look at the README.TXT for info + on how to include wildcard expansion abilities when compiling Artistic Style under Win32. (Thanks for the info + on wildcard-expansion enabling, Nat!!!)
    • +
    + +

    + Artistic Style 1.0.4  (2 December 1998)

    + +
      +
    • Fixed unwanted space-padding around urinary minuses and '-' symbols within exponents + (e.g. 2.5E-5) when using the '-p' option.
    • +
    + +

    + Artistic Style 1.0.3  (1 December 1998)

    + +
      +
    • Control characters now remain in the indented file.
    • +
    • Fixed a bug in which long quoted white-space sequences where mistakenly eliminated + in the '-p' mode.
    • +
    • Fixed unwanted line-breaks in '-ab -p' mode, that in some cases occurred between '//' + and the rest of a line comment.
    • +
    • Fixed handling of '>>=', '<<= ' in '-p' mode.
    • +
    + +

    + Artistic Style 1.0.2 (27 November 1998)

    + +
      +
    • Fixed a SERIOUS bug of missing needed line-breaks in lines immediately after line-comments + when in '-ab' mode.
    • +
    • Support for the 'finally' header.
    • +
    • lines that contain only white-space now become empty lines.
    • +
    + +

    + Artistic Style 1.0.1  (26 November 1998)

    + +
      +
    • Fixed a SERIOUS bug, which lacked a needed line-break between closing brackets and + the headers that follow them (e.g. '} else') when in '-bb' mode. In fixing the bug, I used a variation on a patch + sent by Richard Bullington - THANKS!
    • +
    • Fixed a set of SERIOUS bugs which inserted an empty line into both the start and end + of the reindented file.
    • +
    • Improved documentation of formatting options in the file astyle.html .
    • +
    + +

    + Artistic Style 1.0.0 (24 November 1998)

    + +
      +
    • Indented files now retain the original file name, while the original pre-indented + file is saved with a ".orig"at its end. Thus, after the call "astyle -bb foo.cpp", the newly indented file + will be called "foo.cpp", while a file called "foo.cpp.orig" will contain the original pre-indented + file.
    • +
    • Artistic Style may now be used and /or modified and/or distributed under EITHER + the "Artistic License", or the GNU General Public License (GPL).
    • +
    • Methods with headers that end with 'const' are now properly indented.
    • +
    • Cleaner, more robust, and better documented source code.
    • +
    + +

    + Artistic Style 0.9.2

    + +
      +
    • Fixed a serious bug which led to a maximal supported source code line size of 128 + characters!!!
    • +
    • Maximal supported line size is now 1024 characters.
    • +
    • Fixed a serious bug in the handling of brackets inside '#define' statements.
    • +
    • Fixed a serious bug in which '#include' files containing slashes (i.e. #include <foo_dir/foo> ) where space-padded + when using option '-p' on C, C++ files.
    • +
    + +

    + Artistic Style 0.9.1

    + +
      +
    • Much improved space-padding around pointers ('*') and references ('&') and the + 'operator' key-word in C and C++ source files when using the '-p' space padding option.
    • +
    • Fixed several pointer handling bugs which led to potential core dumps.
    • +
    • Version 0.9.1 now includes all the abilities I am planning for the final 1.0 version, and should be looked + at as the first pre-release version of Artistic Style.
    • +
    + +

    + Artistic Style 0.9.0

    + +
      +
    • Added a formatting layer (ASFormatter.cpp) around the indentation layer (ASBeautifier.cpp).
    • +
    • As a result, the following formatting capabilities have been added: +
        +
      • Bracket ('{' and '}') placement in either ANSI C style or Java style.
      • +
      • Space padding around operators, i.e. (1+2)*3-4 becomes ( 1 + 2 ) * 3 - 4.
      • +
      +
    • +
    • Fixed the 'tab' elimination bug introduced in ASBeautifier 0.8.2.
    • +
    • Fixed a bug which under-indented class headers containing inheritance info.
    • +
    + +

    + ASBeautifier 0.8.2

    + +
      +
    • Fixed indentation problem in brackets around 'struct', and 'union' blocks.
    • +
    • Added recognition for '\' characters in the end of lines.
    • +
    • Improved indentation of post-method-declaration variable initializations.
    • +
    • Several minor bug fixes.
    • +
    + +

    + ASBeautifier 0.8.1

    + +
      +
    • Fixed an important bug in pointer arithmetic which resulted both in phantom indentation errors, and in core-dumps + when trying to indent java files.
    • +
    + +

    + ASBeautifier 0.8.0

    + +
      +
    • This is the first public release of ASBeautifier. It is a direct port to C++ of JSBeautifier + 1.1.1, PLUS extensions to for C++ indentation.
    • +
    • So far, very little beta-testing has been done for the C++ extensions. This should + change extremely with the open-source release (this was the case with JSBeautifier...), so expect ASBeautifier + to become bug-free fast!!!
    • +
    • The C++ source code is not yet written in optimal quality. I rushed a little so that I could release this initial + release as soon as possible. This will soon change.
    • +
    +

    +  

    + +
    + + [SourceForge.net] +
    + +

    +  

    +
  • diff -Nru astyle-1.24/doc/subversion.html astyle-2.01/doc/subversion.html --- astyle-1.24/doc/subversion.html 2010-01-30 19:55:38.000000000 +0000 +++ astyle-2.01/doc/subversion.html 2010-11-29 17:28:18.000000000 +0000 @@ -26,12 +26,11 @@ source files have not been through the extensive system tests that are done before each release. Use reasonable precautions when using source code from the repository.

    - The repository address is "https://astyle.svn.sourceforge.net/svnroot/astyle". - The current version is in the "trunk/AStyle" branch of the repository. The file and directory names in the repository - are case sensitive.

    + The repository address is "https://astyle.svn.sourceforge.net/svnroot/astyle". The current version is in the "trunk/AStyle" + branch of the repository. The file and directory names in the repository are case sensitive.

    - A sample checkout is:
    svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyle"  - "$HOME/astyle"

    + A sample checkout is:
    + svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyle"  "$HOME/astyle"

    You can also browse the subversion repository. This gives you a view into the current status of the project's code without actually checking-out the files.

    @@ -43,20 +42,20 @@

    Two additional Artistic Style projects are available in the repository. They are not maintained for the general - public but are available if you want them. You may have to create your own project files and scripts - to use them. These projects require the Artistic Style project above. They are an extension that requires the - Artistic Style source. All projects, and any additional source required, should be installed in the same top level - folder.

    + public but are available if you want them. You may have to create your own project files and scripts to use them. + These projects require the Artistic Style project above. They are an extension that requires the Artistic Style + source. All projects, and any additional source required, should be installed in the same top level folder.

    AStyleDev

    - AStyleDev contains the development files that are made available in the "Developer Information" section. Refer to that - section for more information.

    + AStyleDev contains the development files that are made available in the "Developer Information" section. Refer + to that section for more information.

    - A sample checkout is:
    svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyleDev"  - "$HOME/astyledev" .

    + A sample checkout is:
    + svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyleDev"  "$HOME/astyledev" + .

    AStyleTest

    @@ -64,15 +63,17 @@

    AStyleTest contains the unit test programs and test scripts for Artistic Style.

    - In addition to the Artistic Style source the unit test program requires the program UnitTest++. - An optional leak finder program can be added if you are using Visual Studio. It's can be found at - Memory(-Leak) and Exception Trace (CRT and COM - Leaks) at "The Code Project". You have to search through the message board at the bottom of the description - to find the most current release. As of January 2010, the most current download is - http://blog.kalmbachnet.de/files/LeakFinder-RC9.zip.

    -

    - A sample checkout is:
    svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyleTest"  - "$HOME/astyletest" .

    + In addition to the Artistic Style source the unit test program requires the program Google Mock. An optional leak finder program can be added if you + are using Visual Studio. It can be found at Memory(-Leak) and Exception Trace (CRT and COM Leaks) at "The + Code Project". You have to search through the message board at the bottom of the description to find the most + current release. As of November 2010, the most current download is + http://blog.kalmbachnet.de/files/LeakFinder-RC11.zip.

    +

    + A sample checkout is:
    + svn  checkout  "https://astyle.svn.sourceforge.net/svnroot/astyle/trunk/AStyleTest"  "$HOME/astyletest" + .

     

    diff -Nru astyle-1.24/doc/vsinstall.html astyle-2.01/doc/vsinstall.html --- astyle-1.24/doc/vsinstall.html 1970-01-01 00:00:00.000000000 +0000 +++ astyle-2.01/doc/vsinstall.html 2010-11-29 17:28:18.000000000 +0000 @@ -0,0 +1,86 @@ + + + + + + .NET Framework SDK + + + + + + + +

    + Visual Studio 2010 C++ Express

    + +

    + Install Instructions for .NET Framework SDK

    + +

    +  

    + +

    + Following are instructions for installing the .NET Framework SDK and adding x64 platforms to an existing project + in a manner similar to the more expensive Visual Studio 2010 editions.

    + +

    + Installing .NET Framework SDK

    + +

    + 64-bit tools are not available on the Visual Studio 2010 C++ Express Edition by default. To enable 64-bit targets, + install the .NET Framework SDK in addition to the Visual Studio 2010 Express Edition. Otherwise, the x64 solution + platform is not available and a warning will occur if you open a project containing a 64-bit target.

    +

    + Install the Windows SDK appropriate for your + operating system. + Use the "Install Now" or "Archive" links to get the SDK. There are downloads for Vista and Windows 7. You can + optionally install the Windows Performance Toolkit, Debugging Tools, and Application Verifier. The Help is also + optional.

    +

    + After installing this package the x64 configurations can be created.

    + +

    + Adding x64 to Project Files

    + +

    + Open a Win32 project. Open the Configuration Manager from the Build menu. In the Active Solution Platform select + New. For the New Platform select x64. Usually you will want to “Copy settings from Win32” and check + “Create new project platforms”. +

    +

    +

    +

    + Open the Properties from the Project menu. There is a new configuration property that needs to be set for the + linker to find the system libraries. Be sure the x64 platform is selected and change "Properties > General + > Platform Toolset", to Windows7.1SDK. Otherwise you will get linker errors + such as "LINK : fatal error LNK1104: cannot open file 'kernel32.lib'". This setting can also optionally be used + for the Win32 platform.

    +

    + The x64 configuration can now be compiled, but the compiles will place the files in the same directories as the + Win32 compiles. To correct this the x64 compiles should be placed in an x64 directory using the $(Platform) + macro.

    +

    + Add the $(Platform) macro to “Configuration Properties > General > Output directory” so the + entry becomes $(SolutionDir)$(Platform)\$(Configuration)\.

    +

    + Add the $(Platform) macro to “Configuration Properties  > General> Intermediate Directory” + so the entry becomes $(Platform)\$(Configuration)\.

    +

    + Check the x64 “Configuration Properties > Linker > Debugging > Generate Program Database File” + for $(ProjectDir)$(PlatformName)\$(ConfigurationName)\$(TargetName)d.pdb.

    +

    + Compile the project. If there are compile errors you may need to add the $(PlatformName) macro +  to other settings as well. For example, if there are user library files the macro may need to be added to + “Configuration Properties > Linker > General > Additional Library Directories”.

    +

    +

    +

    + You should now be able to compile both Win32 and x64 platforms in a manner similar to the more expensive Visual + Studio editions.

    +

    +  

    + + + + diff -Nru astyle-1.24/src/ASBeautifier.cpp astyle-2.01/src/ASBeautifier.cpp --- astyle-1.24/src/ASBeautifier.cpp 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/ASBeautifier.cpp 2010-11-29 17:28:18.000000000 +0000 @@ -66,7 +66,8 @@ isMinConditionalManuallySet = false; isModeManuallySet = false; shouldForceTabIndentation = false; - setSpaceIndentation(4); // also sets minConditionalIndent + setSpaceIndentation(4); + setMinConditionalIndentOption(MINCOND_TWO); setMaxInStatementIndentLength(40); classInitializerTabs = 1; setClassIndent(false); @@ -94,7 +95,7 @@ * ASBeautifier's copy constructor * must explicitly call the base class copy constructor */ -ASBeautifier::ASBeautifier(const ASBeautifier &other) : ASBase(other) +ASBeautifier::ASBeautifier(const ASBeautifier& other) : ASBase(other) { // these don't need to copy the stack waitingBeautifierStack = NULL; @@ -107,16 +108,6 @@ headerStack = new vector; *headerStack = *other.headerStack; - //tempStacks = new vector*>; - //vector*>::iterator iter; - //for (iter = other.tempStacks->begin(); - // iter != other.tempStacks->end(); - // ++iter) - //{ - // vector *newVec = new vector; - // *newVec = **iter; - // tempStacks->push_back(newVec); - //} tempStacks = copyTempStacks(other); blockParenDepthStack = new vector; @@ -199,6 +190,7 @@ blockCommentNoBeautify = other.blockCommentNoBeautify; previousLineProbationTab = other.previousLineProbationTab; fileType = other.fileType; + minConditionalOption = other.minConditionalOption; minConditionalIndent = other.minConditionalIndent; parenDepth = other.parenDepth; indentLength = other.indentLength; @@ -246,7 +238,7 @@ * * @param iter a pointer to the ASSourceIterator or ASStreamIterator object. */ -void ASBeautifier::init(ASSourceIterator *iter) +void ASBeautifier::init(ASSourceIterator* iter) { sourceIterator = iter; init(); @@ -400,9 +392,6 @@ indentString = "\t"; indentLength = length; shouldForceTabIndentation = forceTabs; - - if (!isMinConditionalManuallySet) - minConditionalIndent = indentLength * 2; } /** @@ -414,9 +403,6 @@ { indentString = string(length, ' '); indentLength = length; - - if (!isMinConditionalManuallySet) - minConditionalIndent = indentLength * 2; } /** @@ -438,21 +424,28 @@ } /** - * set the minimum indentation between two lines in a multi-line condition. + * set the minimum conditional indentation option. * - * @param min minimal indentation length. + * @param min minimal indentation option. */ -void ASBeautifier::setMinConditionalIndentLength(int min) +void ASBeautifier::setMinConditionalIndentOption(int min) { - minConditionalIndent = min; + minConditionalOption = min; } /** - * set min conditional manually set flag + * set minConditionalIndent from the minConditionalOption. */ -void ASBeautifier::setMinConditionalManuallySet(bool state) +void ASBeautifier::setMinConditionalIndentLength() { - isMinConditionalManuallySet = state; + if (minConditionalOption == MINCOND_ZERO) + minConditionalIndent = 0; + else if (minConditionalOption == MINCOND_ONE) + minConditionalIndent = indentLength; + else if (minConditionalOption == MINCOND_ONEHALF) + minConditionalIndent = indentLength / 2; + // minConditionalOption = INDENT_TWO + else minConditionalIndent = indentLength * 2; } /** @@ -597,16 +590,6 @@ } /** - * get the state of the isMinConditionalManuallySet flag - * - * @return the state of isMinConditionalManuallySet. - */ -bool ASBeautifier::getMinConditionalManuallySet() -{ - return isMinConditionalManuallySet; -} - -/** * get mode manually set flag */ bool ASBeautifier::getModeManuallySet() @@ -691,23 +674,15 @@ } /** - * check if there are any indented lines ready to be read by nextLine() + * get the state of the preprocessor indentation option. + * If true, preprocessor "define" lines will be indented. + * If false, preprocessor "define" lines will be unchanged. * - * @return are there any indented lines ready? + * @return state of preprocessorIndent option. */ -bool ASBeautifier::hasMoreLines() const +bool ASBeautifier::getPreprocessorIndent(void) { - return sourceIterator->hasMoreLines(); -} - -/** - * get the next indented line. - * - * @return indented line. - */ -string ASBeautifier::nextLine() -{ - return beautify(sourceIterator->nextLine()); + return preprocessorIndent; } /** @@ -718,7 +693,7 @@ * @return the indented line. * @param originalLine the original unindented line. */ -string ASBeautifier::beautify(const string &originalLine) +string ASBeautifier::beautify(const string& originalLine) { string line; bool isInLineComment = false; @@ -745,7 +720,7 @@ int i; int iPrelim; string outBuffer; // the newly idented line is buffered here - const string *lastLineHeader = NULL; + const string* lastLineHeader = NULL; currentHeader = NULL; lineStartsInComment = isInComment; @@ -806,13 +781,12 @@ // handle preprocessor commands // except C# region and endregion - if (!isInComment - && (line[0] == '#' || backslashEndsPrevLine) - && line.compare(0, 7, "#region") != 0 - && line.compare(0, 10, "#endregion") != 0) + && line.length() > 0 + && ((line[0] == '#' && !isIndentedPreprocessor(line, 0)) + || backslashEndsPrevLine)) { - if (line[0] == '#') + if (line.length() > 0 && line[0] == '#') { string preproc = trim(string(line.c_str() + 1)); @@ -827,7 +801,7 @@ { if (!isInDefineDefinition) { - ASBeautifier *defineBeautifier; + ASBeautifier* defineBeautifier; // this is the original beautifier isInDefineDefinition = true; @@ -848,9 +822,12 @@ // push a new beautifier into the stack waitingBeautifierStackLengthStack->push_back(waitingBeautifierStack->size()); activeBeautifierStackLengthStack->push_back(activeBeautifierStack->size()); - waitingBeautifierStack->push_back(new ASBeautifier(*this)); + if (activeBeautifierStackLengthStack->back() == 0) + waitingBeautifierStack->push_back(new ASBeautifier(*this)); + else + waitingBeautifierStack->push_back(new ASBeautifier(*activeBeautifierStack->back())); } - else if (preproc.compare(0, 4/*2*/, "else") == 0) + else if (preproc.compare(0, 4, "else") == 0) { if (waitingBeautifierStack && !waitingBeautifierStack->empty()) { @@ -870,7 +847,7 @@ else if (preproc.compare(0, 5, "endif") == 0) { int stackLength; - ASBeautifier *beautifier; + ASBeautifier* beautifier; if (waitingBeautifierStackLengthStack && !waitingBeautifierStackLengthStack->empty()) { @@ -901,8 +878,6 @@ // check if the last char is a backslash if (line.length() > 0) backslashEndsPrevLine = (line[line.length() - 1] == '\\'); - else - backslashEndsPrevLine = false; // check if this line ends a multi-line #define // if so, use the #define's cloned beautifier for the line's indentation @@ -910,7 +885,7 @@ if (!backslashEndsPrevLine && isInDefineDefinition && !isInDefine) { string beautifiedLine; - ASBeautifier *defineBeautifier; + ASBeautifier* defineBeautifier; isInDefineDefinition = false; defineBeautifier = activeBeautifierStack->back(); @@ -962,6 +937,7 @@ || (*headerStack)[i] == &AS_STRUCT || (*headerStack)[i] == &AS_UNION || (*headerStack)[i] == &AS_CONST + || (*headerStack)[i] == &AS_VOLATILE || (*headerStack)[i] == &AS_INTERFACE || (*headerStack)[i] == &AS_THROWS || (*headerStack)[i] == &AS_STATIC)) @@ -1005,6 +981,7 @@ && headerStack->size() >= 2 && (*headerStack)[headerStack->size()-2] == &AS_CLASS && (*headerStack)[headerStack->size()-1] == &AS_OPEN_BRACKET + && line.length() > 0 && line[0] == '}' && bracketBlockStateStack->back() == true) --tabCount; @@ -1015,6 +992,7 @@ && headerStack->size() >= 2 && (*headerStack)[headerStack->size()-2] == &AS_SWITCH && (*headerStack)[headerStack->size()-1] == &AS_OPEN_BRACKET + && line.length() > 0 && line[0] == '}') --tabCount; @@ -1161,9 +1139,8 @@ blockCommentNoIndent = false; // ok to indent next comment continue; } - // treat C# '#region' and '#endregion' statements as a line comment - else if (isSharpStyle() && - (line.compare(i, 7, "#region") == 0 || line.compare(i, 10, "#endregion") == 0)) + // treat indented preprocessor lines as a line comment + else if (line[0] == '#' && isIndentedPreprocessor(line, i)) { isInLineComment = true; } @@ -1179,13 +1156,11 @@ // if we have reached this far then we are NOT in a comment or string of special character... - // SQL if formatted in ASEnhancer - if (isInBeautifySQL) - continue; - if (probationHeader != NULL) { - if (((probationHeader == &AS_STATIC || probationHeader == &AS_CONST) && ch == '{') + if (((probationHeader == &AS_STATIC + || probationHeader == &AS_CONST + || probationHeader == &AS_VOLATILE) && ch == '{') || (probationHeader == &AS_SYNCHRONIZED && ch == '(')) { // insert the probation header as a new header @@ -1200,7 +1175,9 @@ if (previousLineProbation && ch == '{' && !(blockIndent - && (probationHeader == &AS_CONST || probationHeader == &AS_STATIC))) + && (probationHeader == &AS_CONST + || probationHeader == &AS_VOLATILE + || probationHeader == &AS_STATIC))) { tabCount++; previousLineProbationTab = true; @@ -1240,10 +1217,7 @@ { if (--templateDepth <= 0) { - if (isInTemplate) - ch = ';'; - else - ch = 't'; + ch = ';'; isInTemplate = false; templateDepth = 0; } @@ -1338,6 +1312,7 @@ || isSharpAccessor || isSharpDelegate || isInExtern + || getNextWord(line, i) == "new" || (isInDefine && (prevNonSpaceCh == '(' || isLegalNameChar(prevNonSpaceCh)))); @@ -1395,7 +1370,7 @@ && (*headerStack).back() == &AS_CLASS) { int nextChar = getNextProgramCharDistance(line, i); - if (line[nextChar] == '}') + if ((int)line.length() > nextChar && line[nextChar] == '}') tabCount--; } } @@ -1440,24 +1415,7 @@ if (isPotentialHeader) { - const string *newHeader = findHeader(line, i, headers); - - if (newHeader != NULL) - { - char peekChar = peekNextChar(line, i + newHeader->length() - 1); - - // is not a header if part of a definition - if (peekChar == ',' || peekChar == ')') - newHeader = NULL; - // the following accessor definitions are NOT headers - // goto default; is NOT a header - // default(int) keyword in C# is NOT a header - else if ((newHeader == &AS_GET || newHeader == &AS_SET || newHeader == &AS_DEFAULT) - && (peekChar == ';' || peekChar == '(')) - { - newHeader = NULL; - } - } + const string* newHeader = findHeader(line, i, headers); if (newHeader != NULL) { @@ -1570,12 +1528,14 @@ } else if (newHeader == &AS_STATIC || newHeader == &AS_SYNCHRONIZED - || (newHeader == &AS_CONST && isCStyle())) + || (newHeader == &AS_CONST && isCStyle()) + || (newHeader == &AS_VOLATILE && isCStyle())) { if (!headerStack->empty() && (headerStack->back() == &AS_STATIC || headerStack->back() == &AS_SYNCHRONIZED - || headerStack->back() == &AS_CONST)) + || headerStack->back() == &AS_CONST + || headerStack->back() == &AS_VOLATILE)) { isIndentableHeader = false; } @@ -1623,7 +1583,7 @@ if (ch == '?') isInQuestion = true; - // special handling of 'case' statements + // special handling of colons if (ch == ':') { if ((int) line.length() > i + 1 && line[i+1] == ':') // look for :: @@ -1666,6 +1626,7 @@ else if (isCStyle() && prevNonSpaceCh == ')' && !isInCase) { isInClassInitializer = true; + isInStatement = false; // so an inStatement indent will register if (i == 0) tabCount += classInitializerTabs; } @@ -1700,7 +1661,7 @@ inStatementIndentStack->pop_back(); // handle commas - // previous "isInStatement" will be from an assignment operator + // previous "isInStatement" will be from an assignment operator or class initializer if (ch == ',' && parenDepth == 0 && !isInStatement && !isNonInStatementArray) { // is comma at end of line @@ -1796,6 +1757,8 @@ closingBracketReached = true; isInAsmOneLine = false; + if (i == 0) + spaceTabCount = 0; // added for release 1.24 // TODO: remove at the appropriate time @@ -1808,7 +1771,7 @@ int headerPlace = indexOf(*headerStack, &AS_OPEN_BRACKET); if (headerPlace != -1) { - const string *popped = headerStack->back(); + const string* popped = headerStack->back(); while (popped != &AS_OPEN_BRACKET) { headerStack->pop_back(); @@ -1868,7 +1831,7 @@ // (otherwise 'struct XXX' statements would be wrongly interpreted...) if (!isInTemplate && !(isCStyle() && parenDepth > 0)) { - const string *newHeader = findHeader(line, i, preBlockStatements); + const string* newHeader = findHeader(line, i, preBlockStatements); if (newHeader != NULL && !(isCStyle() && newHeader == &AS_CLASS && isInEnum)) // is it 'enum class' { @@ -1889,7 +1852,7 @@ continue; } } - const string *foundIndentableHeader = findHeader(line, i, indentableHeaders); + const string* foundIndentableHeader = findHeader(line, i, indentableHeaders); if (foundIndentableHeader != NULL) { @@ -1910,8 +1873,11 @@ // "new" operator is a pointer, not a calculation if (findKeyword(line, i, AS_NEW)) { - if (prevNonSpaceCh == '=' && isInStatement && !inStatementIndentStack->empty()) - inStatementIndentStack->back() = 0; + if (isInStatement && !inStatementIndentStack->empty()) + { + if (prevNonSpaceCh == '=' && isInStatement && !inStatementIndentStack->empty()) + inStatementIndentStack->back() = 0; + } } if (isCStyle()) @@ -1950,8 +1916,8 @@ if (isPotentialOperator) { // Check if an operator has been reached. - const string *foundAssignmentOp = findOperator(line, i, assignmentOperators); - const string *foundNonAssignmentOp = findOperator(line, i, nonAssignmentOperators); + const string* foundAssignmentOp = findOperator(line, i, assignmentOperators); + const string* foundNonAssignmentOp = findOperator(line, i, nonAssignmentOperators); // Since findHeader's boundry checking was not used above, it is possible // that both an assignment op and a non-assignment op where found, @@ -2090,7 +2056,7 @@ if (isInDefine) { - if (outBuffer[0] == '#') + if (outBuffer.length() > 0 && outBuffer[0] == '#') { string preproc = trim(string(outBuffer.c_str() + 1)); if (preproc.compare(0, 6, "define") == 0) @@ -2172,7 +2138,7 @@ /** * register an in-statement indent. */ -void ASBeautifier::registerInStatementIndent(const string &line, int i, int spaceTabCount, +void ASBeautifier::registerInStatementIndent(const string& line, int i, int spaceTabCount, int tabIncrementIn, int minIndent, bool updateParenStack) { int inStatementIndent; @@ -2240,7 +2206,7 @@ * get distance to the next non-white space, non-comment character in the line. * if no such character exists, return the length remaining to the end of the line. */ -int ASBeautifier::getNextProgramCharDistance(const string &line, int i) const +int ASBeautifier::getNextProgramCharDistance(const string& line, int i) const { bool inComment = false; int remainingCharNum = line.length() - i; @@ -2279,7 +2245,7 @@ } // check if a specific line position contains a header. -const string* ASBeautifier::findHeader(const string &line, int i, +const string* ASBeautifier::findHeader(const string& line, int i, const vector* possibleHeaders) const { assert(isCharPotentialHeader(line, i)); @@ -2301,17 +2267,23 @@ return header; if (isLegalNameChar(line[wordEnd])) continue; - // is not a header if part of a definition const char peekChar = peekNextChar(line, wordEnd - 1); + // is not a header if part of a definition if (peekChar == ',' || peekChar == ')') break; + // the following accessor definitions are NOT headers + // goto default; is NOT a header + // default(int) keyword in C# is NOT a header + else if ((header == &AS_GET || header == &AS_SET || header == &AS_DEFAULT) + && (peekChar == ';' || peekChar == '(')) + break; return header; } return NULL; } // check if a specific line position contains an operator. -const string* ASBeautifier::findOperator(const string &line, int i, +const string* ASBeautifier::findOperator(const string& line, int i, const vector* possibleOperators) const { assert(isCharPotentialOperator(line[i])); @@ -2337,7 +2309,7 @@ * @param container a vector of strings. * @param element the element to find . */ -int ASBeautifier::indexOf(vector &container, const string *element) +int ASBeautifier::indexOf(vector &container, const string* element) { vector::const_iterator where; @@ -2366,7 +2338,7 @@ * @return the trimmed line. * @param str the line to trim. */ -string ASBeautifier::trim(const string &str) +string ASBeautifier::trim(const string& str) { int start = 0; @@ -2386,7 +2358,7 @@ * Copy tempStacks for the copy constructor. * The value of the vectors must also be copied. */ -vector*>* ASBeautifier::copyTempStacks(const ASBeautifier &other) const +vector*>* ASBeautifier::copyTempStacks(const ASBeautifier& other) const { vector*> *tempStacksNew = new vector*>; vector*>::iterator iter; @@ -2421,7 +2393,7 @@ * used for all vectors except tempStacks */ template -void ASBeautifier::deleteContainer(T &container) +void ASBeautifier::deleteContainer(T& container) { if (container != NULL) { @@ -2467,7 +2439,7 @@ * used for all vectors */ template -void ASBeautifier::initContainer(T &container, T value) +void ASBeautifier::initContainer(T& container, T value) { // since the ASFormatter object is never deleted, // the existing vectors must be deleted before creating new ones @@ -2492,26 +2464,26 @@ * * @return true if line ends with a comma, otherwise false. */ -bool ASBeautifier::statementEndsWithComma(string &line, int index) +bool ASBeautifier::statementEndsWithComma(string& line, int index) { assert(line[index] == '='); - bool isInComment = false; - bool isInQuote = false; + bool isInComment_ = false; + bool isInQuote_ = false; int parenCount = 0; size_t lineLength = line.length(); size_t i = 0; - char quoteChar = ' '; + char quoteChar_ = ' '; for (i = index + 1; i < lineLength; ++i) { char ch = line[i]; - if (isInComment) + if (isInComment_) { if (line.compare(i, 2, "*/") == 0) { - isInComment = false; + isInComment_ = false; ++i; } continue; @@ -2523,17 +2495,17 @@ continue; } - if (isInQuote) + if (isInQuote_) { - if (ch == quoteChar) - isInQuote = false; + if (ch == quoteChar_) + isInQuote_ = false; continue; } if (ch == '"' || ch == '\'') { - isInQuote = true; - quoteChar = ch; + isInQuote_ = true; + quoteChar_ = ch; continue; } @@ -2546,7 +2518,7 @@ break; else { - isInComment = true; + isInComment_ = true; ++i; continue; } @@ -2557,8 +2529,8 @@ if (ch == ')') parenCount--; } - if (isInComment - || isInQuote + if (isInComment_ + || isInQuote_ || parenCount > 0) return false; @@ -2627,9 +2599,6 @@ { assert(line[currPos] == ','); - if (currPos == 0) - return 0; - // get first word on a line size_t indent = line.find_first_not_of(" \t"); if (indent == string::npos || !isLegalNameChar(line[indent])) @@ -2646,13 +2615,87 @@ return 0; // point to second word or assignment operator - indent = line.find_last_not_of(" \t", indent); + indent = line.find_first_not_of(" \t", indent); if (indent == string::npos || indent >= currPos) return 0; return indent; } +/** + * get the next word on a line + * the argument 'currPos' must point to the current position. + * + * @return is the previous word or an empty string if none found. + */ +string ASBeautifier::getNextWord(const string& line, size_t currPos) const +{ + size_t lineLength = line.length(); + // get the last legal word (may be a number) + if (currPos == lineLength - 1) + return string(); + + size_t start = line.find_first_not_of(" \t", currPos+1); + if (start == string::npos || !isLegalNameChar(line[start])) + return string(); -} // end namespace astyle + size_t end; // end of the current word + for (end = start+1; end <= lineLength; end++) + { + if (!isLegalNameChar(line[end]) || line[end] == '.') + break; + } + + return line.substr(start, end-start); +} + +/** + * Check if a preprocessor directive is always indented. + * C# "region" and "endregion" are always indented. + * C/C++ "pragma omp" is always indented. + * + * @return is true or false. + */ +bool ASBeautifier::isIndentedPreprocessor(const string& line, size_t currPos) const +{ + assert(line[0] == '#'); + string nextWord = getNextWord(line, currPos); + if (nextWord == "region" || nextWord == "endregion") + return true; + // is it #pragma omp + if (nextWord == "pragma") + { + // find pragma + size_t start = line.find("pragma"); + if (start == string::npos || !isLegalNameChar(line[start])) + return false; + // bypass pragma + for (; start < line.length(); start++) + { + if (!isLegalNameChar(line[start])) + break; + } + start++; + if (start >= line.length()) + return false; + // point to start of second word + start = line.find_first_not_of(" \t", start); + if (start == string::npos) + return false; + // point to end of second word + size_t end; + for (end = start; end < line.length(); end++) + { + if (!isLegalNameChar(line[end])) + break; + } + // check for "pragma omp" + string word = line.substr(start, end - start); + if (word == "omp") + return true; + } + return false; +} + +} // end namespace astyle diff -Nru astyle-1.24/src/ASEnhancer.cpp astyle-2.01/src/ASEnhancer.cpp --- astyle-1.24/src/ASEnhancer.cpp 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/ASEnhancer.cpp 2010-11-29 17:28:18.000000000 +0000 @@ -58,6 +58,7 @@ int _indentLength, string _indentString, bool _caseIndent, + bool _preprocessorIndent, bool _emptyLineFill) { // formatting variables from ASFormatter and ASBeautifier @@ -69,6 +70,7 @@ useTabs = false; caseIndent = _caseIndent; + preprocessorIndent = _preprocessorIndent; emptyLineFill = _emptyLineFill; quoteChar = '\''; @@ -85,7 +87,7 @@ sw.switchBracketCount = 0; sw.unindentDepth = 0; sw.unindentCase = false; - swVector.clear(); + switchStack.clear(); // other variables nextLineIsEventIndent = false; @@ -103,7 +105,7 @@ * * @param line the original formatted line will be updated if necessary. */ -void ASEnhancer::enhance(string &line, bool isInSQL) +void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) { bool isSpecialChar = false; // is a backslash escape character @@ -217,19 +219,24 @@ bool isPotentialKeyword = isCharPotentialHeader(line, i); - // ---------------- process event tables -------------------------------------- + // ---------------- wxWidgets and MFC macros ---------------------------------- if (isPotentialKeyword) { if (findKeyword(line, i, "BEGIN_EVENT_TABLE") - || findKeyword(line, i, "BEGIN_MESSAGE_MAP")) + || findKeyword(line, i, "BEGIN_DISPATCH_MAP") + || findKeyword(line, i, "BEGIN_EVENT_MAP") + || findKeyword(line, i, "BEGIN_MESSAGE_MAP") + || findKeyword(line, i, "BEGIN_PROPPAGEIDS")) { nextLineIsEventIndent = true; break; } - if (findKeyword(line, i, "END_EVENT_TABLE") - || findKeyword(line, i, "END_MESSAGE_MAP")) + || findKeyword(line, i, "END_DISPATCH_MAP") + || findKeyword(line, i, "END_EVENT_MAP") + || findKeyword(line, i, "END_MESSAGE_MAP") + || findKeyword(line, i, "END_PROPPAGEIDS")) { isInEventTable = false; break; @@ -252,7 +259,7 @@ if (isPotentialKeyword && findKeyword(line, i, "switch")) { switchDepth++; - swVector.push_back(sw); // save current variables + switchStack.push_back(sw); // save current variables sw.switchBracketCount = 0; sw.unindentCase = false; // don't clear case until end of switch i += 5; // bypass switch statement @@ -261,7 +268,9 @@ // just want unindented switch statements from this point - if (caseIndent || switchDepth == 0) + if (caseIndent + || switchDepth == 0 + || (isInPreprocessor && !preprocessorIndent)) { // bypass the entire word if (isPotentialKeyword) @@ -278,7 +287,7 @@ if (isInEventTable || isInDeclareSection) { - if (line[0] != '#') + if (line.length() == 0 || line[0] != '#') indentLine(line, 1); } @@ -293,24 +302,24 @@ * @param i the line index of the case statement. * @return the line index of the colon. */ -size_t ASEnhancer::findCaseColon(string &line, size_t caseIndex) const +size_t ASEnhancer::findCaseColon(string& line, size_t caseIndex) const { size_t i = caseIndex; - bool isInQuote = false; - char quoteChar = ' '; + bool isInQuote_ = false; + char quoteChar_ = ' '; for (; i < line.length(); i++) { - if (isInQuote) + if (isInQuote_) { if (line[i] == '\\') { i++; continue; } - else if (line[i] == quoteChar) // check ending quote + else if (line[i] == quoteChar_) // check ending quote { - isInQuote = false; - quoteChar = ' '; + isInQuote_ = false; + quoteChar_ = ' '; continue; } else @@ -320,8 +329,8 @@ } if (line[i] == '\'' || line[i] == '\"') // check opening quote { - isInQuote = true; - quoteChar = line[i]; + isInQuote_ = true; + quoteChar_ = line[i]; continue; } if (line[i] == ':') @@ -343,7 +352,7 @@ * @param unindent the number of tabsets to insert. * @return the number of characters inserted. */ -int ASEnhancer::indentLine(string &line, int indent) const +int ASEnhancer::indentLine(string& line, int indent) const { if (line.length() == 0 && ! emptyLineFill) @@ -354,12 +363,12 @@ if (useTabs) // if formatted with tabs { charsToInsert = indent; // tabs to insert - line.insert((size_t) 0, charsToInsert, '\t'); // insert the tabs + line.insert(0U, charsToInsert, '\t'); // insert the tabs } else { charsToInsert = indent * indentLength; // compute chars to insert - line.insert((size_t)0, charsToInsert, ' '); // insert the spaces + line.insert(0U, charsToInsert, ' '); // insert the spaces } return charsToInsert; @@ -373,7 +382,7 @@ * @param index the current line index. * @return true if a hit. */ -bool ASEnhancer::isBeginDeclareSectionSQL(string &line, size_t index) const +bool ASEnhancer::isBeginDeclareSectionSQL(string& line, size_t index) const { string word; size_t hits = 0; @@ -422,7 +431,7 @@ * @param index the current line index. * @return true if a hit. */ -bool ASEnhancer::isEndDeclareSectionSQL(string &line, size_t index) const +bool ASEnhancer::isEndDeclareSectionSQL(string& line, size_t index) const { string word; size_t hits = 0; @@ -470,7 +479,7 @@ * @param index the current line index. * @return the new line index. */ -size_t ASEnhancer::processSwitchBlock(string &line, size_t index) +size_t ASEnhancer::processSwitchBlock(string& line, size_t index) { size_t i = index; bool isPotentialKeyword = isCharPotentialHeader(line, i); @@ -493,9 +502,9 @@ sw.switchBracketCount--; if (sw.switchBracketCount == 0) // if end of switch statement { - switchDepth--; // one less switch - sw = swVector.back(); // restore sw struct - swVector.pop_back(); // remove last entry from stack + switchDepth--; + sw = switchStack.back(); + switchStack.pop_back(); } return i; } @@ -546,7 +555,7 @@ * @param unindent the number of tabsets to erase. * @return the number of characters erased. */ -int ASEnhancer::unindentLine(string &line, int unindent) const +int ASEnhancer::unindentLine(string& line, int unindent) const { size_t whitespace = line.find_first_not_of(" \t"); diff -Nru astyle-1.24/src/ASFormatter.cpp astyle-2.01/src/ASFormatter.cpp --- astyle-1.24/src/ASFormatter.cpp 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/ASFormatter.cpp 2010-11-29 17:28:18.000000000 +0000 @@ -130,7 +130,7 @@ * * @param sourceIterator a pointer to the ASSourceIterator or ASStreamIterator object. */ -void ASFormatter::init(ASSourceIterator *si) +void ASFormatter::init(ASSourceIterator* si) { buildLanguageVectors(); fixOptionVariableConflicts(); @@ -140,6 +140,7 @@ getIndentLength(), getIndentString(), getCaseIndent(), + getPreprocessorIndent(), getEmptyLineFill()); sourceIterator = si; @@ -148,7 +149,7 @@ initContainer(structStack, new vector); parenStack->push_back(0); // parenStack must contain this default entry initContainer(bracketTypeStack, new vector); - bracketTypeStack->push_back(NULL_TYPE); + bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry currentHeader = NULL; currentLine = ""; @@ -160,6 +161,8 @@ previousNonWSChar = ' '; quoteChar = '"'; charNum = 0; + checksumIn = 0; + checksumOut = 0; leadingSpaces = 0; formattedLineCommentNum = 0; preprocBracketTypeStackSize = 0; @@ -179,6 +182,7 @@ isInComment = false; noTrimCommentContinuation = false; isInPreprocessor = false; + isInPreprocessorBeautify = false; doesLineStartComment = false; lineEndsInCommentOnly = false; lineIsLineCommentOnly = false; @@ -213,15 +217,17 @@ shouldBreakLineAtNextChar = false; passedSemicolon = false; passedColon = false; - clearNonInStatement = false; + isImmediatelyPostNonInStmt = false; + isCharImmediatelyPostNonInStmt = false; isInTemplate = false; - isInBlParen = false; +// isInBlParen = false; isImmediatelyPostComment = false; isImmediatelyPostLineComment = false; isImmediatelyPostEmptyBlock = false; isImmediatelyPostPreprocessor = false; isImmediatelyPostReturn = false; isImmediatelyPostOperator = false; + isImmediatelyPostPointerOrReference = false; isCharImmediatelyPostReturn = false; isCharImmediatelyPostOperator = false; isCharImmediatelyPostComment = false; @@ -230,6 +236,7 @@ isCharImmediatelyPostOpenBlock = false; isCharImmediatelyPostCloseBlock = false; isCharImmediatelyPostTemplate = false; + isCharImmediatelyPostPointerOrReference = false; breakCurrentOneLineBlock = false; isInHorstmannRunIn = false; currentLineBeginsWithBracket = false; @@ -293,7 +300,7 @@ setBlockIndent(false); setBracketIndent(false); } - else if (formattingStyle == STYLE_KandR) + else if (formattingStyle == STYLE_KR) { setBracketFormatMode(LINUX_MODE); setBlockIndent(false); @@ -353,8 +360,8 @@ else setSpaceIndentation(8); } - if (!getMinConditionalManuallySet()) - setMinConditionalIndentLength(getIndentLength() / 2); + // always for Linux style + setMinConditionalIndentOption(MINCOND_ONEHALF); } else if (formattingStyle == STYLE_HORSTMANN) { @@ -378,6 +385,7 @@ setAddBracketsMode(true); } + setMinConditionalIndentLength(); // add-one-line-brackets implies keep-one-line-blocks if (shouldAddOneLineBrackets) setBreakOneLineBlocksMode(false); @@ -394,7 +402,7 @@ string ASFormatter::nextLine() { - const string *newHeader; + const string* newHeader; bool isInVirginLine = isVirgin; isCharImmediatelyPostComment = false; isPreviousCharPostComment = false; @@ -411,7 +419,7 @@ else if (!getNextChar()) { breakLine(); - return beautify(readyFormattedLine); + continue; } else // stuff to do when reading a new character... { @@ -420,11 +428,6 @@ && currentLineBeginsWithBracket // lineBeginsWith('{') && previousCommandChar == ' ') previousCommandChar = '{'; - if (clearNonInStatement) - { - isNonInStatementArray = false; - clearNonInStatement = false; - } if (isInHorstmannRunIn) isInLineBreak = false; if (!isWhiteSpace(currentChar)) @@ -434,6 +437,7 @@ isCharImmediatelyPostTemplate = false; isCharImmediatelyPostReturn = false; isCharImmediatelyPostOperator = false; + isCharImmediatelyPostPointerOrReference = false; isCharImmediatelyPostOpenBlock = false; isCharImmediatelyPostCloseBlock = false; } @@ -498,7 +502,7 @@ || isSequenceReached("#warning")) { // check for horstmann run-in - if (formattedLine[0] == '{') + if (formattedLine.length() > 0 && formattedLine[0] == '{') { isInLineBreak = true; isInHorstmannRunIn = false; @@ -531,7 +535,7 @@ { isInPreprocessor = true; // check for horstmann run-in - if (formattedLine[0] == '{') + if (formattedLine.length() > 0 && formattedLine[0] == '{') { isInLineBreak = true; isInHorstmannRunIn = false; @@ -565,6 +569,11 @@ isImmediatelyPostOperator = false; isCharImmediatelyPostOperator = true; } + if (isImmediatelyPostPointerOrReference) + { + isImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostPointerOrReference = true; + } // reset isImmediatelyPostHeader information if (isImmediatelyPostHeader) @@ -648,66 +657,17 @@ } // Check if in template declaration, e.g. foo or foo - // If so, set isInTemplate to true if (!isInTemplate && currentChar == '<') { - int maxTemplateDepth = 0; - templateDepth = 0; - for (size_t i = charNum; - i < currentLine.length(); - i++) - { - char currentChar = currentLine[i]; - - if (currentChar == '<') - { - templateDepth++; - maxTemplateDepth++; - } - else if (currentChar == '>') - { - templateDepth--; - if (templateDepth == 0) - { - // this is a template! - isInTemplate = true; - templateDepth = maxTemplateDepth; - break; - } - } - else if (currentLine.compare(i, 2, "&&") == 0 - || currentLine.compare(i, 2, "||") == 0) - { - // this is not a template -> leave... - isInTemplate = false; - break; - } - else if (currentChar == ',' // comma, e.g. A - || currentChar == '&' // reference, e.g. A - || currentChar == '*' // pointer, e.g. A - || currentChar == ':' // ::, e.g. std::string - || currentChar == '[' // [] e.g. string[] - || currentChar == ']' // [] e.g. string[] - || currentChar == '(' // (...) e.g. function definition - || currentChar == ')') // (...) e.g. function definition - { - continue; - } - else if (!isLegalNameChar(currentChar) && !isWhiteSpace(currentChar)) - { - // this is not a template -> leave... - isInTemplate = false; - break; - } - } + checkIfTemplateOpener(); } // handle parenthesies if (currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) { parenStack->back()++; - if (currentChar == '[') - isInBlParen = true; +// if (currentChar == '[') +// isInBlParen = true; } else if (currentChar == ')' || currentChar == ']' || (isInTemplate && currentChar == '>')) { @@ -728,8 +688,8 @@ isInHeader = false; isImmediatelyPostHeader = true; } - if (currentChar == ']') - isInBlParen = false; +// if (currentChar == ']') +// isInBlParen = false; if (currentChar == ')') { foundCastOperator = false; @@ -753,6 +713,7 @@ foundPreCommandHeader = false; isInPotentialCalculation = false; isJavaStaticConstructor = false; + isCharImmediatelyPostNonInStmt = false; needHeaderOpeningBracket = false; isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); @@ -818,8 +779,10 @@ else isInIndentableStruct = false; - if (isBracketType(bracketType, ARRAY_NIS_TYPE) && !isBracketType(bracketType, SINGLE_LINE_TYPE)) - clearNonInStatement = true; + if (isNonInStatementArray + && (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket + || peekNextChar() == ';')) // check for "};" added V2.01 + isImmediatelyPostNonInStmt = true; } // format brackets @@ -848,7 +811,8 @@ && !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE))) && isOkToBreakBlock(bracketTypeStack->back())) // check for array - || (isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + || (previousCommandChar == '{' // added 9/30/2010 + && isBracketType(bracketTypeStack->back(), ARRAY_TYPE) && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) && isNonInStatementArray)) { @@ -901,23 +865,7 @@ if (newHeader != NULL) { - char peekChar = ASBase::peekNextChar(currentLine, charNum + newHeader->length() - 1); - - // is not a header if part of a definition - if (peekChar == ',' || peekChar == ')') - newHeader = NULL; - // the following accessor definitions are NOT headers - // goto default; is NOT a header - else if ((newHeader == &AS_GET || newHeader == &AS_SET || newHeader == &AS_DEFAULT) - && peekChar == ';') - { - newHeader = NULL; - } - } - - if (newHeader != NULL) - { - const string *previousHeader; + const string* previousHeader; // recognize closing headers of do..while, if..else, try..catch..finally if ((newHeader == &AS_ELSE && currentHeader == &AS_IF) @@ -970,7 +918,7 @@ // in C# 'catch' can be either a paren or non-paren header if (shouldPadHeader && (!isNonParenHeader || (currentHeader == &AS_CATCH && peekNextChar() == '(')) - && charNum < (int) currentLine.length() && !isWhiteSpace(currentLine[charNum+1])) + && charNum < (int) currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum+1])) appendSpacePad(); // Signal that a header has been reached @@ -1227,13 +1175,14 @@ } // process pointers and references - // check new header to elimnate things like '&&' sequence + // check newHeader to elimnate things like '&&' sequence if (isCStyle() && (newHeader == &AS_MULT || newHeader == &AS_BIT_AND) && isPointerOrReference() && !isDereferenceOrAddressOf()) { formatPointerOrReference(); + isImmediatelyPostPointerOrReference = true; continue; } @@ -1266,14 +1215,23 @@ } } - if ((shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens) - && (currentChar == '(' || currentChar == ')')) + if ((currentChar == '(' || currentChar == ')') + && (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens)) { padParens(); continue; } + // bypass the entire operator + if (newHeader != NULL && newHeader->length() > 1) + { + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + continue; + } + appendCurrentChar(); + } // end of while loop * end of while loop * end of while loop * end of while loop // return a beautified (i.e. correctly indented) line. @@ -1288,6 +1246,8 @@ isLineReady = true; // signal a waiting readyFormattedLine beautifiedLine = beautify(""); previousReadyFormattedLineLength = 0; + // call the enhancer for new empty lines + enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); } else // format the current formatted line { @@ -1295,17 +1255,23 @@ horstmannIndentInStatement = horstmannIndentChars; beautifiedLine = beautify(readyFormattedLine); previousReadyFormattedLineLength = readyFormattedLineLength; - // the enhancer is not called for new empty lines - // or no-indent line comments + // the enhancer is not called for no-indent line comments if (!lineCommentNoBeautify) - enhancer->enhance(beautifiedLine, isInBeautifySQL); + enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); horstmannIndentChars = 0; lineCommentNoBeautify = lineCommentNoIndent; lineCommentNoIndent = false; - isInBeautifySQL = isInExecSQL; + if (isCharImmediatelyPostNonInStmt) + { + isNonInStatementArray = false; + isCharImmediatelyPostNonInStmt = false; + } + isInPreprocessorBeautify = isInPreprocessor; // used by ASEnhancer + isInBeautifySQL = isInExecSQL; // used by ASEnhancer } prependEmptyLine = false; + assert(computeChecksumOut(beautifiedLine)); return beautifiedLine; } @@ -1735,7 +1701,10 @@ if (appendOpeningBracket) currentLine = "{"; // append bracket that was removed from the previous line else + { currentLine = sourceIterator->nextLine(emptyLineWasDeleted); + assert(computeChecksumIn(currentLine)); + } // reset variables for new line inLineNumber++; isInCase = false; @@ -1746,9 +1715,7 @@ previousChar = ' '; if (currentLine.length() == 0) - { currentLine = string(" "); // a null is inserted if this is not done - } // unless reading in the first line of the file, break a new line. if (!isVirgin) @@ -1756,6 +1723,12 @@ else isVirgin = false; + if (isImmediatelyPostNonInStmt) + { + isCharImmediatelyPostNonInStmt = true; + isImmediatelyPostNonInStmt = false; + } + // check if is in preprocessor before line trimming // a blank line after a \ will remove the flag isImmediatelyPostPreprocessor = isInPreprocessor; @@ -1766,8 +1739,9 @@ if (passedSemicolon) isInExecSQL = false; initNewLine(); + currentChar = currentLine[charNum]; - if (isInHorstmannRunIn && previousNonWSChar == '{') + if (isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) isInLineBreak = false; isInHorstmannRunIn = false; @@ -1781,17 +1755,13 @@ && lineIsEmpty && isBracketType((*bracketTypeStack)[bracketTypeStack->size()-1], COMMAND_TYPE)) { - // but do NOT delete an empty line between comments if blocks are being broken - if (!(shouldBreakBlocks || shouldBreakClosingHeaderBlocks) - || !isImmediatelyPostCommentOnly - || !commentAndHeaderFollows()) + if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) { isInPreprocessor = isImmediatelyPostPreprocessor; // restore lineIsEmpty = false; return getNextLine(true); } } - return true; } else @@ -1834,9 +1804,7 @@ i += indent - 1; } } - // correct the format if EXEC SQL is not a hanging indent - if (i < leadingSpaces) - currentLine.insert((size_t)0, leadingSpaces - i, ' '); + // this will correct the format if EXEC SQL is not a hanging indent trimContinuationLine(); return; } @@ -1917,7 +1885,7 @@ * @param sequence the sequence to append. * @param canBreakLine if true, a registered line-break */ -void ASFormatter::appendSequence(const string &sequence, bool canBreakLine) +void ASFormatter::appendSequence(const string& sequence, bool canBreakLine) { if (canBreakLine && isInLineBreak) breakLine(); @@ -1966,7 +1934,6 @@ // queue an empty line prepend request if one exists prependEmptyLine = isPrependPostBlockEmptyLineRequested; - readyFormattedLine = formattedLine; if (isAppendPostBlockEmptyLineRequested) { isAppendPostBlockEmptyLineRequested = false; @@ -1977,6 +1944,7 @@ isPrependPostBlockEmptyLineRequested = false; } + readyFormattedLine = formattedLine; formattedLine = ""; } @@ -2038,7 +2006,13 @@ returnVal = (isCommandType ? COMMAND_TYPE : ARRAY_TYPE); } - if (isOneLineBlockReached(currentLine, charNum)) + int foundOneLineBlock = isOneLineBlockReached(currentLine, charNum); + // this assumes each array definition is on a single line + // (foundOneLineBlock == 2) is a one line block followed by a comma + if (foundOneLineBlock == 2 && returnVal == COMMAND_TYPE) + returnVal = ARRAY_TYPE; + + if (foundOneLineBlock > 0) // found one line block returnVal = (BracketType)(returnVal | SINGLE_LINE_TYPE); if (isBracketType(returnVal, ARRAY_TYPE) && isNonInStatementArrayBracket()) @@ -2056,7 +2030,7 @@ * * @return whether line is empty */ -bool ASFormatter::isEmptyLine(const string &line) const +bool ASFormatter::isEmptyLine(const string& line) const { return line.find_first_not_of(" \t") == string::npos; } @@ -2077,33 +2051,37 @@ if (!isCStyle()) return false; - if (currentChar == '&' && previousChar == '&') + if ((currentChar == '&' && previousChar == '&') +// || isInBlParen + || isCharImmediatelyPostOperator) return false; - if (previousNonWSChar == '=' || isCharImmediatelyPostReturn) - return true; - - if (currentHeader == &AS_CATCH) + if (previousNonWSChar == '=' + || previousNonWSChar == '(' + || previousNonWSChar == '[' + || currentHeader == &AS_CATCH + || isCharImmediatelyPostReturn) return true; // get the last legal word (may be a number) string lastWord = getPreviousWord(currentLine, charNum); if (lastWord.empty()) - lastWord[0] = ' '; + lastWord = " "; char nextChar = peekNextChar(); // check for preceding or following numeric values if (isdigit(lastWord[0]) - || isdigit(nextChar)) + || isdigit(nextChar) + || nextChar == '!') return false; - // checks on other chars - if (isLegalNameChar(lastWord[0]) - && isLegalNameChar(nextChar) - && parenStack->back() > 0) + // checks on operators in parens + if (parenStack->back() > 0 + && isLegalNameChar(lastWord[0]) + && isLegalNameChar(nextChar)) { // if followed by an assignment it is a pointer or reference - size_t nextNum = currentLine.find_first_of("=;)", charNum + 1); + size_t nextNum = currentLine.find_first_of("=;)]", charNum + 1); if (nextNum != string::npos && currentLine[nextNum] == '=') return true; @@ -2115,6 +2093,17 @@ return false; } + // checks on operators in parens with following '(' + if (parenStack->back() > 0 + && nextChar == '(' + && previousNonWSChar != ',' + && previousNonWSChar != '(' + && previousNonWSChar != '!' + && previousNonWSChar != '&' + && previousNonWSChar != '*' + && previousNonWSChar != '|') + return false; + if (nextChar == '-' || nextChar == '+') { @@ -2162,6 +2151,7 @@ if (previousNonWSChar == '=' || previousNonWSChar == ',' || previousNonWSChar == '.' + || previousNonWSChar == '{' || previousNonWSChar == '>' || previousNonWSChar == '<' || isCharImmediatelyPostReturn) @@ -2190,12 +2180,16 @@ || currentLine[nextChar] == ',')) return false; + if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + && parenStack->back() == 0) + return false; + string lastWord = getPreviousWord(currentLine, charNum); if (lastWord == "else" || lastWord == "delete") return true; bool isDA = (!(isLegalNameChar(previousNonWSChar) || previousNonWSChar == '>') - || !isLegalNameChar(peekNextChar()) + || (!isLegalNameChar(peekNextChar()) && peekNextChar() != '/') || (ispunct(previousNonWSChar) && previousNonWSChar != '.') || isCharImmediatelyPostReturn); @@ -2216,6 +2210,11 @@ int prNum = charNum; int lineLength = (int) currentLine.length(); + + // check for end of line + if (peekNextChar() == ' ') + return false; + // check space before if (prNum < 1 || currentLine[prNum-1] != ' ') @@ -2232,7 +2231,7 @@ prNum++; // check space after - if (prNum + 1 < lineLength + if (prNum + 1 <= lineLength && currentLine[prNum+1] != ' ') return false; @@ -2328,27 +2327,31 @@ * i.e. if the currently reached '{' character is closed * with a complimentry '}' elsewhere on the current line, *. - * @return has a one-line bracket been reached? + * @return 0 = one-line bracket has not been reached. + * 1 = one-line bracket has been reached. + * 2 = one-line bracket has been reached and is followed by a comma. */ -bool ASFormatter::isOneLineBlockReached(string& line, int startChar) const +int ASFormatter::isOneLineBlockReached(string& line, int startChar) const { assert(line[startChar] == '{'); - bool isInComment = false; - bool isInQuote = false; + bool isInComment_ = false; + bool isInQuote_ = false; int bracketCount = 1; int lineLength = line.length(); - char quoteChar = ' '; + char quoteChar_ = ' '; + char ch = ' '; + char prevCh = ' '; for (int i = startChar + 1; i < lineLength; ++i) { - char ch = line[i]; + ch = line[i]; - if (isInComment) + if (isInComment_) { if (line.compare(i, 2, "*/") == 0) { - isInComment = false; + isInComment_ = false; ++i; } continue; @@ -2360,17 +2363,17 @@ continue; } - if (isInQuote) + if (isInQuote_) { - if (ch == quoteChar) - isInQuote = false; + if (ch == quoteChar_) + isInQuote_ = false; continue; } if (ch == '"' || ch == '\'') { - isInQuote = true; - quoteChar = ch; + isInQuote_ = true; + quoteChar_ = ch; continue; } @@ -2379,7 +2382,7 @@ if (line.compare(i, 2, "/*") == 0) { - isInComment = true; + isInComment_ = true; ++i; continue; } @@ -2390,10 +2393,21 @@ --bracketCount; if (bracketCount == 0) - return true; + { + // is this an array? + if (parenStack->back() == 0 && prevCh != '}') + { + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if (peekNum != string::npos && line[peekNum] == ',') + return 2; + } + return 1; + } + if (!isWhiteSpace(ch)) + prevCh = ch; } - return false; + return 0; } /** @@ -2442,49 +2456,52 @@ * @param the first line to check * @return the next non-whitespace substring. */ -string ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/) const +string ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const { bool isFirstLine = true; - bool needReset = false; - string nextLine = firstLine; + bool needReset = shouldReset; + string nextLine_ = firstLine; size_t firstChar= string::npos; // find the first non-blank text, bypassing all comments. - bool isInComment = false; + bool isInComment_ = false; while (sourceIterator->hasMoreLines()) { if (isFirstLine) isFirstLine = false; else { - nextLine = sourceIterator->peekNextLine(); + nextLine_ = sourceIterator->peekNextLine(); needReset = true; } - firstChar = nextLine.find_first_not_of(" \t"); + firstChar = nextLine_.find_first_not_of(" \t"); if (firstChar == string::npos) { - if (endOnEmptyLine && !isInComment) + if (endOnEmptyLine && !isInComment_) break; continue; } - if (nextLine.compare(firstChar, 2, "/*") == 0) - isInComment = true; + if (nextLine_.compare(firstChar, 2, "/*") == 0) + { + firstChar += 2; + isInComment_ = true; + } - if (isInComment) + if (isInComment_) { - firstChar = nextLine.find("*/", firstChar); + firstChar = nextLine_.find("*/", firstChar); if (firstChar == string::npos) continue; firstChar += 2; - isInComment = false; - firstChar = nextLine.find_first_not_of(" \t", firstChar); + isInComment_ = false; + firstChar = nextLine_.find_first_not_of(" \t", firstChar); if (firstChar == string::npos) continue; } - if (nextLine.compare(firstChar, 2, "//") == 0) + if (nextLine_.compare(firstChar, 2, "//") == 0) continue; // found the next text @@ -2494,10 +2511,10 @@ if (needReset) sourceIterator->peekReset(); if (firstChar == string::npos) - nextLine = ""; + nextLine_ = ""; else - nextLine = nextLine.substr(firstChar); - return nextLine; + nextLine_ = nextLine_.substr(firstChar); + return nextLine_; } /** @@ -2552,14 +2569,13 @@ * append the current bracket inside the end of line comments * currentChar contains the bracket, it will be appended to formattedLine * formattedLineCommentNum is the comment location on formattedLine - * returns true f appended, false if not */ void ASFormatter::appendCharInsideComments(void) { if (formattedLineCommentNum == string::npos) // does the comment start on the previous line? { appendCurrentChar(); // don't attach - return; // false; + return; } assert(formattedLine.compare(formattedLineCommentNum, 2, "//") == 0 || formattedLine.compare(formattedLineCommentNum, 2, "/*") == 0); @@ -2567,10 +2583,10 @@ // find the previous non space char size_t end = formattedLineCommentNum; size_t beg = formattedLine.find_last_not_of(" \t", end-1); - if (beg == string::npos) // is the previous line comment only? + if (beg == string::npos) { appendCurrentChar(); // don't attach - return; // false; + return; } beg++; @@ -2585,7 +2601,7 @@ breakLine(); else if (isCharImmediatelyPostLineComment) shouldBreakLineAtNextChar = true; - return; // true; + return; } /** @@ -2596,13 +2612,11 @@ * * @param *newOperator the operator to be padded */ -void ASFormatter::padOperators(const string *newOperator) +void ASFormatter::padOperators(const string* newOperator) { assert(newOperator != NULL); bool shouldPad = (newOperator != &AS_COLON_COLON - && newOperator != &AS_PAREN_PAREN - && newOperator != &AS_BLPAREN_BLPAREN && newOperator != &AS_PLUS_PLUS && newOperator != &AS_MINUS_MINUS && newOperator != &AS_NOT @@ -2611,6 +2625,7 @@ && !(newOperator == &AS_MINUS && isInExponent()) && !((newOperator == &AS_PLUS || newOperator == &AS_MINUS) // check for unary plus or minus && (previousNonWSChar == '(' + || previousNonWSChar == '[' || previousNonWSChar == '=' || previousNonWSChar == ',')) && !(newOperator == &AS_PLUS && isInExponent()) @@ -2633,7 +2648,7 @@ // pad before operator if (shouldPad - && !isInBlParen +// && !isInBlParen && !(newOperator == &AS_COLON && !foundQuestionMark) && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) && currentLine.find(':', charNum+1) == string::npos) @@ -2642,24 +2657,18 @@ appendSequence(*newOperator); goForward(newOperator->length() - 1); - // since this block handles '()' and '[]', - // the parenStack must be updated here accordingly! - if (newOperator == &AS_PAREN_PAREN - || newOperator == &AS_BLPAREN_BLPAREN) - parenStack->back()--; - currentChar = (*newOperator)[newOperator->length() - 1]; // pad after operator // but do not pad after a '-' that is a unary-minus. if (shouldPad - && !isInBlParen +// && !isInBlParen && !isBeforeAnyComment() && !(newOperator == &AS_PLUS && isUnaryOperator()) && !(newOperator == &AS_MINUS && isUnaryOperator()) && !(currentLine.compare(charNum + 1, 1, ";") == 0) && !(currentLine.compare(charNum + 1, 2, "::") == 0) && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) - && currentLine[charNum+1] == '[') + && peekNextChar() == '[') ) appendSpaceAfter(); @@ -2681,7 +2690,7 @@ // check for cast char peekedChar = peekNextChar(); if (currentChar == '*' - && (int) currentLine.length() > charNum + && (int) currentLine.length() > charNum + 1 && currentLine[charNum+1] == '*') { size_t nextChar = currentLine.find_first_not_of(" \t", charNum+2); @@ -2696,6 +2705,13 @@ return; } + // check for a padded space and remove it + if (charNum > 0 + && !isWhiteSpace(currentLine[charNum-1]) + && formattedLine.length() > 0 + && isWhiteSpace(formattedLine[formattedLine.length()-1])) + formattedLine.erase(formattedLine.length()-1); + // do this before bumping charNum bool isOldPRCentered = isPointerOrReferenceCentered(); @@ -2747,32 +2763,56 @@ sequenceToInsert = "**"; goForward(1); } + bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: size_t charNumSave = charNum; - // goForward() to convert tabs to spaces, if necessary, - // and move following characters to preceding characters - // this may not work every time with tab characters - for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + // if a comment follows don't align, just space pad + if (isBeforeAnyComment()) { - goForward(1); - formattedLine.append(1, currentLine[i]); + appendSpacePad(); + formattedLine.append(sequenceToInsert); + appendSpaceAfter(); + return; + } + // if this is not the last thing on the line + if ((int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) + { + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + { + goForward(1); + formattedLine.append(1, currentLine[i]); + } } - // whitespace should be at least 2 chars + // find space padding after size_t wsAfter = currentLine.find_first_not_of(" \t", charNumSave + 1); - if (wsAfter == string::npos) + if (wsAfter == string::npos || isBeforeAnyComment()) wsAfter = 0; else wsAfter = wsAfter - charNumSave - 1; - if (wsBefore + wsAfter < 2) + // don't pad before scope resolution operator, but pad after + if (isAfterScopeResolution) { - size_t charsToAppend = (2 - (wsBefore + wsAfter)); - formattedLine.append(charsToAppend, ' '); - spacePadNum += charsToAppend; - if (wsBefore == 0) wsBefore++; - if (wsAfter == 0) wsAfter++; - } - // insert the pointer or reference char - size_t padAfter = (wsBefore + wsAfter) / 2; - formattedLine.insert(formattedLine.length() - padAfter, sequenceToInsert); + size_t lastText = formattedLine.find_last_not_of(" \t"); + formattedLine.insert(lastText + 1, sequenceToInsert); + appendSpacePad(); + } + // whitespace should be at least 2 chars to center + else + { + if (wsBefore + wsAfter < 2) + { + size_t charsToAppend = (2 - (wsBefore + wsAfter)); + formattedLine.append(charsToAppend, ' '); + spacePadNum += charsToAppend; + if (wsBefore == 0) wsBefore++; + if (wsAfter == 0) wsAfter++; + } + // insert the pointer or reference char + size_t padAfter = (wsBefore + wsAfter) / 2; + formattedLine.insert(formattedLine.length() - padAfter, sequenceToInsert); + } } else if (pointerAlignment == ALIGN_NAME) { @@ -2783,26 +2823,40 @@ sequenceToInsert = "**"; goForward(1); } - // goForward() to convert tabs to spaces, if necessary, - // and move following characters to preceding characters - // this may not work every time with tab characters - for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) - { - goForward(1); - formattedLine.append(1, currentLine[i]); + bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: + // if this is not the last thing on the line + if (!isBeforeAnyComment() + && (int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) + { + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + { + goForward(1); + formattedLine.append(1, currentLine[i]); + } + } + // don't pad before scope resolution operator + if (startNum != string::npos && isAfterScopeResolution) + { + size_t lastText = formattedLine.find_last_not_of(" \t"); + if (lastText + 1 < formattedLine.length()) + formattedLine.erase(lastText + 1); } - appendSequence(sequenceToInsert, false); // if no space before * then add one - if (startNum != string::npos - && !isWhiteSpace(formattedLine[startNum+1])) + else if (formattedLine.length() <= startNum + 1 + || !isWhiteSpace(formattedLine[startNum+1])) { formattedLine.insert(startNum+1 , 1, ' '); spacePadNum++; } + appendSequence(sequenceToInsert, false); // if old pointer or reference is centered, remove a space if (isOldPRCentered && formattedLine.length() > startNum+1 - && isWhiteSpace(formattedLine[startNum+1])) + && isWhiteSpace(formattedLine[startNum+1]) + && !isBeforeAnyComment()) { formattedLine.erase(startNum+1, 1); spacePadNum--; @@ -2842,17 +2896,14 @@ size_t prevCh = formattedLine.find_last_not_of(" \t"); if (prevCh == string::npos) prevCh = 0; - if (formattedLine.length() > 0 && isWhiteSpace(formattedLine[prevCh+1])) + if (prevCh + 1 < formattedLine.length() + && isWhiteSpace(formattedLine[prevCh+1])) { spacePadNum -= (formattedLine.length() - 1 - prevCh); formattedLine.erase(prevCh+1); } - if (pointerAlignment == ALIGN_TYPE) - { - appendSequence(sequenceToInsert, false); - } - else if (pointerAlignment == ALIGN_MIDDLE - || pointerAlignment == ALIGN_NAME) + if (pointerAlignment == ALIGN_MIDDLE + || pointerAlignment == ALIGN_NAME) { appendSpacePad(); appendSequence(sequenceToInsert, false); @@ -2890,6 +2941,8 @@ // if last char is a bracket the previous whitespace is an indent if (formattedLine[i] == '{') spacesOutsideToDelete = 0; + else if (isCharImmediatelyPostPointerOrReference) + spacesOutsideToDelete = 0; else { spacesOutsideToDelete -= i; @@ -2907,8 +2960,7 @@ // trace //cout << traceLineNumber << " " << *prevWordH << endl; } - else if (prevWord == "return" // don't unpad return statements - || prevWord == "*") // don't unpad multiply or pointer + else if (prevWord == "return") // don't unpad return statements { prevIsParenHeader = true; // trace @@ -2940,8 +2992,9 @@ if (shouldPadParensOutside || prevIsParenHeader) spacesOutsideToDelete--; else if (lastChar == '|' // check for || - || lastChar == '&' // check for && + || lastChar == '&' // check for && || lastChar == ',' + || (lastChar == '(' && shouldPadParensInside) || (lastChar == '>' && !foundCastOperator) || lastChar == '<' || lastChar == '?' @@ -2950,7 +3003,7 @@ || lastChar == '=' || lastChar == '+' || lastChar == '-' - || (lastChar == '*' && isInPotentialCalculation) + || lastChar == '*' || lastChar == '/' || lastChar == '%') spacesOutsideToDelete--; @@ -2985,7 +3038,7 @@ } // convert tab to space if requested if (shouldConvertTabs - && (int)currentLine.length() > charNum + && (int)currentLine.length() > charNum + 1 && currentLine[charNum+1] == '\t') currentLine[charNum+1] = ' '; @@ -3000,7 +3053,7 @@ //if(spacesOutsideToDelete > 0 || spacesInsideToDelete > 0) // cout << traceLineNumber << " " << spacesOutsideToDelete << '(' << spacesInsideToDelete << endl; } - else if (currentChar == ')' /*|| currentChar == ']'*/) + else if (currentChar == ')') { spacesOutsideToDelete = 0; spacesInsideToDelete = formattedLine.length(); @@ -3028,21 +3081,20 @@ appendCurrentChar(); // unpad close paren outside + // close parens outside are left unchanged if (shouldUnPadParens) { - // may have end of line comments - size_t j = currentLine.find_first_not_of(" \t", charNum + 1); - if (j != string::npos) - if (currentLine[j] == '[' || currentLine[j] == ']') - spacesOutsideToDelete = j - charNum - 1; - if (shouldPadParensOutside) - spacesOutsideToDelete--; - - if (spacesOutsideToDelete > 0) - { - currentLine.erase(charNum + 1, spacesOutsideToDelete); - spacePadNum -= spacesOutsideToDelete; - } + //size_t j = currentLine.find_first_not_of(" \t", charNum + 1); + //if (j != string::npos) + // spacesOutsideToDelete = j - charNum - 1; + //if (shouldPadParensOutside) + // spacesOutsideToDelete--; + + //if (spacesOutsideToDelete > 0) + //{ + // currentLine.erase(charNum + 1, spacesOutsideToDelete); + // spacePadNum -= spacesOutsideToDelete; + //} } // pad close paren outside @@ -3051,7 +3103,8 @@ if (peekedCharOutside != ';' && peekedCharOutside != ',' && peekedCharOutside != '.' - && peekedCharOutside != '-') // check for -> + && peekedCharOutside != '-' // check for -> + && peekedCharOutside != ']') appendSpaceAfter(); // trace @@ -3086,6 +3139,8 @@ if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) // lineBeginsWith('{') { currentChar = ' '; // remove bracket from current line + if (parenStack->size() > 1) + parenStack->pop_back(); currentLine[charNum] = currentChar; appendOpeningBracket = true; // append bracket to following line } @@ -3105,6 +3160,7 @@ // should a following comment break from the bracket? // must break the line AFTER the bracket if (isBeforeComment() + && formattedLine.length() > 0 && formattedLine[0] == '{' && isOkToBreakBlock(bracketType) && (bracketFormatMode == BREAK_MODE @@ -3122,6 +3178,7 @@ { if (isOkToBreakBlock(bracketType) && !(isCharImmediatelyPostComment && isCharImmediatelyPostLineComment) // don't attach if two comments on the line + && !isImmediatelyPostPreprocessor && peekNextChar() != '}' // don't attach { } && previousCommandChar != '{' // don't attach { { && previousCommandChar != '}' // don't attach } { @@ -3201,8 +3258,8 @@ isImmediatelyPostEmptyBlock = true; if ((!(previousCommandChar == '{' && isPreviousBracketBlockRelated)) // this '{' does not close an empty block - && isOkToBreakBlock(bracketType) // astyle is allowed to break on line blocks - && !isImmediatelyPostEmptyBlock) // this '}' does not immediately follow an empty block + && isOkToBreakBlock(bracketType)) // astyle is allowed to break on line blocks +// && !isImmediatelyPostEmptyBlock) /* removed 9/5/10 */ // this '}' does not immediately follow an empty block { breakLine(); appendCurrentChar(); @@ -3257,7 +3314,7 @@ // TODO: attach bracket to line-end comment appendCurrentChar(); // don't attach } - else if (isCharImmediatelyPostLineComment) + else if (isCharImmediatelyPostLineComment && !isBracketType(bracketType, SINGLE_LINE_TYPE)) { appendCharInsideComments(); } @@ -3270,7 +3327,7 @@ { // if bracket is broken or not an assignment if (currentLineBeginsWithBracket // lineBeginsWith('{') - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + && !isBracketType(bracketType, SINGLE_LINE_TYPE)) { appendSpacePad(); appendCurrentChar(false); // OK to attach @@ -3306,7 +3363,7 @@ if (currentLineBeginsWithBracket && (int)currentLineFirstBracketNum == charNum - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + && !isBracketType(bracketType, SINGLE_LINE_TYPE)) shouldBreakLineAtNextChar = true; } else if (bracketFormatMode == HORSTMANN_MODE) @@ -3361,7 +3418,9 @@ else if (currentChar == '}') { // does this close the first opening bracket in the array? - if (!isBracketType(bracketType, SINGLE_LINE_TYPE) ) + // must check if the block is still a single line because of anonymous statements + if (!isBracketType(bracketType, SINGLE_LINE_TYPE) + || formattedLine.find('{') == string::npos) breakLine(); appendCurrentChar(); @@ -3385,6 +3444,7 @@ if (!isOkToBreakBlock(bracketTypeStack->back())) return; // true; + // make sure the line begins with a bracket size_t lastText = formattedLine.find_last_not_of(" \t"); if (lastText == string::npos || formattedLine[lastText] != '{') return; // false; @@ -3519,7 +3579,7 @@ * used for all vectors except bracketTypeStack */ template -void ASFormatter::deleteContainer(T &container) +void ASFormatter::deleteContainer(T& container) { if (container != NULL) { @@ -3546,7 +3606,7 @@ * used for all vectors except bracketTypeStack */ template -void ASFormatter::initContainer(T &container, T value) +void ASFormatter::initContainer(T& container, T value) { // since the ASFormatter object is never deleted, // the existing vectors must be deleted before creating new ones @@ -3612,10 +3672,14 @@ * if a header follows, the comments are kept as part of the header block. * firstLine must contain the start of the comment. */ -void ASFormatter::checkForFollowingHeader(const string& firstLine) +void ASFormatter::checkForHeaderFollowingComment(const string& firstLine) { + assert(isInComment || isInLineComment); + // this is called ONLY IF shouldBreakBlocks is TRUE. + assert(shouldBreakBlocks); // look ahead to find the next non-comment text string nextText = peekNextText(firstLine, true); + if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) return; @@ -3624,13 +3688,8 @@ if (newHeader == NULL) return; - // may need to break if a header follows - bool isClosingHeader = (newHeader == &AS_ELSE - || newHeader == &AS_CATCH - || newHeader == &AS_FINALLY); - // if a closing header, reset break unless break is requested - if (isClosingHeader) + if (isClosingHeader(newHeader)) { if (!shouldBreakClosingHeaderBlocks) isPrependPostBlockEmptyLineRequested = false; @@ -3674,23 +3733,28 @@ /** * determine if the next line starts a comment - * and a header follows the comment or comments + * and a header follows the comment or comments. */ -bool ASFormatter::commentAndHeaderFollows() const +bool ASFormatter::commentAndHeaderFollows() { + // called ONLY IF shouldDeleteEmptyLines and shouldBreakBlocks are TRUE. + assert(shouldDeleteEmptyLines && shouldBreakBlocks); + // is the next line a comment - string nextLine = sourceIterator->peekNextLine(); - size_t firstChar = nextLine.find_first_not_of(" \t"); + if (!sourceIterator->hasMoreLines()) + return false; + string nextLine_ = sourceIterator->peekNextLine(); + size_t firstChar = nextLine_.find_first_not_of(" \t"); if (firstChar == string::npos - || !(nextLine.compare(firstChar, 2, "//") == 0 - || nextLine.compare(firstChar, 2, "/*") == 0)) + || !(nextLine_.compare(firstChar, 2, "//") == 0 + || nextLine_.compare(firstChar, 2, "/*") == 0)) { sourceIterator->peekReset(); return false; } - // if next line is a comment, find the next non-comment text - string nextText = peekNextText(nextLine, true); + // find the next non-comment text, and reset + string nextText = peekNextText(nextLine_, false, true); if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) return false; @@ -3699,12 +3763,12 @@ if (newHeader == NULL) return false; - bool isClosingHeader = (newHeader == &AS_ELSE - || newHeader == &AS_CATCH - || newHeader == &AS_FINALLY); - - if (isClosingHeader && !shouldBreakClosingHeaderBlocks) + // if a closing header, reset break unless break is requested + if (isClosingHeader(newHeader) && !shouldBreakClosingHeaderBlocks) + { + isAppendPostBlockEmptyLineRequested = false; return false; + } return true; } @@ -3717,7 +3781,7 @@ */ bool ASFormatter::isCurrentBracketBroken() const { - assert(bracketTypeStack->size() > 0); + assert(bracketTypeStack->size() > 1); bool breakBracket = false; size_t bracketTypeStackEnd = bracketTypeStack->size()-1; @@ -3804,7 +3868,10 @@ && previousCommandChar != ';' && !isBracketType(bracketTypeStack->back(), ARRAY_TYPE) && isOkToBreakBlock(bracketTypeStack->back())) - breakLine(); + { + isInLineBreak = true; + shouldBreakLineAtNextChar = true; + } } else { @@ -3833,7 +3900,7 @@ isInComment = true; isImmediatelyPostLineComment = false; - if (spacePadNum != 0) + if (spacePadNum != 0 && !isInLineBreak) adjustComments(); formattedLineCommentNum = formattedLine.length(); @@ -3851,14 +3918,14 @@ else if (bracketFormatMode == ATTACH_MODE) { // if the bracket was not attached? - if (formattedLine[0] == '{' + if (formattedLine.length() > 0 && formattedLine[0] == '{' && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) isInLineBreak = true; } else if (bracketFormatMode == HORSTMANN_MODE) { // should a run-in statement be attached? - if (formattedLine[0] == '{') + if (formattedLine.length() > 0 && formattedLine[0] == '{') formatRunIn(); } } @@ -3877,11 +3944,10 @@ // if previous line is a line comment or if previous line is '{' if (doesLineStartComment && !isImmediatelyPostEmptyLine - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment + && !isImmediatelyPostCommentOnly && previousCommandChar != '{') { - checkForFollowingHeader(currentLine.substr(charNum-1)); + checkForHeaderFollowingComment(currentLine.substr(charNum-1)); } } @@ -3926,7 +3992,8 @@ { assert(isSequenceReached("//")); - if (currentLine[charNum+2] == '\xf2') // check for windows line marker + if ((int)currentLine.length() > charNum + 2 + && currentLine[charNum+2] == '\xf2') // check for windows line marker isAppendPostBlockEmptyLineRequested = false; isInLineComment = true; @@ -3941,7 +4008,7 @@ lineCommentNoIndent = true; } // move comment if spaces were added or deleted - if (lineCommentNoIndent == false && spacePadNum != 0) + if (lineCommentNoIndent == false && spacePadNum != 0 && !isInLineBreak) adjustComments(); formattedLineCommentNum = formattedLine.length(); @@ -3965,7 +4032,7 @@ } else if (bracketFormatMode == BREAK_MODE) { - if (formattedLine[0] == '{') + if (formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; } else @@ -3991,10 +4058,9 @@ if (lineIsLineCommentOnly && previousCommandChar != '{' && !isImmediatelyPostEmptyLine - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment) + && !isImmediatelyPostCommentOnly) { - checkForFollowingHeader(currentLine.substr(charNum-1)); + checkForHeaderFollowingComment(currentLine.substr(charNum-1)); } } @@ -4105,14 +4171,11 @@ } else if (bracketFormatMode == HORSTMANN_MODE) { - if (!lineCommentNoIndent) - formatRunIn(); - else - isInLineBreak = true; + formatRunIn(); } else if (bracketFormatMode == BREAK_MODE) { - if (formattedLine[0] == '{') + if (formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; } else @@ -4133,7 +4196,7 @@ int ASFormatter::getNextLineCommentAdjustment() { assert(foundClosingHeader && previousNonWSChar == '}'); - if (charNum < 1) + if (charNum < 1) // "else" is in column 1 return 0; size_t lastBracket = currentLine.rfind('}', charNum - 1); if (lastBracket != string::npos) @@ -4141,6 +4204,7 @@ return 0; } +// for console build only LineEndFormat ASFormatter::getLineEndFormat() const { return lineEnd; @@ -4165,10 +4229,10 @@ } /** - * get the previous word - * the argument 'end' must point to the search start. + * get the previous word on a line + * the argument 'currPos' must point to the current position. * - * @return is the previous word. + * @return is the previous word or an empty string if none found. */ string ASFormatter::getPreviousWord(const string& line, int currPos) const { @@ -4235,12 +4299,12 @@ // if a blank line does not preceed this // or last line is not a one line block, attach header bool previousLineIsEmpty = isEmptyLine(formattedLine); - bool previousLineIsOneLineBlock = false; + int previousLineIsOneLineBlock = 0; size_t firstBracket = findNextChar(formattedLine, '{'); if (firstBracket != string::npos) previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBracket); if (!previousLineIsEmpty - && !previousLineIsOneLineBlock) + && previousLineIsOneLineBlock == 0) { isInLineBreak = false; appendSpacePad(); @@ -4276,7 +4340,9 @@ return false; // find the next semi-colon - size_t nextSemiColon = findNextChar(currentLine, ';', charNum+1); + size_t nextSemiColon = charNum; + if (currentChar != ';') + nextSemiColon = findNextChar(currentLine, ';', charNum+1); if (nextSemiColon == string::npos) return false; @@ -4287,6 +4353,7 @@ currentLine.insert(nextSemiColon + 1, " }"); // add opening bracket currentLine.insert(charNum, "{ "); + assert(computeChecksumIn("{}")); currentChar = '{'; // remove extra spaces if (!shouldAddOneLineBrackets) @@ -4303,7 +4370,7 @@ * * @param line the line to be searched. * @param searchChar the char to find. - * @param searchStart the char to find. + * @param searchStart the start position on the line (default is 0). * @return the position on the line or string::npos if not found. */ size_t ASFormatter::findNextChar(string& line, char searchChar, int searchStart /*0*/) @@ -4320,6 +4387,8 @@ if (endComment == string::npos) return string::npos; i = endComment + 2; + if (i >= line.length()) + return string::npos; } if (line[i] == '\'' || line[i] == '\"') { @@ -4358,7 +4427,7 @@ * @param index the current line index. * @return true if the struct has access modifiers. */ -bool ASFormatter::isStructAccessModified(string &firstLine, size_t index) const +bool ASFormatter::isStructAccessModified(string& firstLine, size_t index) const { assert(firstLine[index] == '{'); assert(isCStyle()); @@ -4366,48 +4435,66 @@ bool isFirstLine = true; bool needReset = false; size_t bracketCount = 1; - string nextLine = firstLine.substr(index + 1); + string nextLine_ = firstLine.substr(index + 1); - // find the first non-blank text, bypassing all comments. - bool isInComment = false; + // find the first non-blank text, bypassing all comments and quotes. + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; while (sourceIterator->hasMoreLines()) { if (isFirstLine) isFirstLine = false; else { - nextLine = sourceIterator->peekNextLine(); + nextLine_ = sourceIterator->peekNextLine(); needReset = true; } // parse the line - for (size_t i = 0; i < nextLine.length(); i++) + for (size_t i = 0; i < nextLine_.length(); i++) { - if (isWhiteSpace(nextLine[i])) + if (isWhiteSpace(nextLine_[i])) continue; - if (nextLine.compare(i, 2, "/*") == 0) - isInComment = true; - if (isInComment) + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) { - i = nextLine.find("*/", i); - if (i == string::npos) + if (nextLine_.compare(i, 2, "*/") == 0) { - i = nextLine.length(); - continue; + isInComment_ = false; + ++i; } - i++; - isInComment = false; continue; } - if (nextLine.compare(i, 2, "//") == 0) + if (nextLine_[i] == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (nextLine_[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (nextLine_[i] == '"' || nextLine_[i] == '\'') + { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) { - i = nextLine.length(); + i = nextLine_.length(); continue; } // handle brackets - if (nextLine[i] == '{') - bracketCount++; - if (nextLine[i] == '}') - bracketCount--; + if (nextLine_[i] == '{') + ++bracketCount; + if (nextLine_[i] == '}') + --bracketCount; if (bracketCount == 0) { if (needReset) @@ -4415,17 +4502,17 @@ return false; } // check for access modifiers - if (isCharPotentialHeader(nextLine, i)) + if (isCharPotentialHeader(nextLine_, i)) { - if (findKeyword(nextLine, i, AS_PUBLIC) - || findKeyword(nextLine, i, AS_PRIVATE) - || findKeyword(nextLine, i, AS_PROTECTED)) + if (findKeyword(nextLine_, i, AS_PUBLIC) + || findKeyword(nextLine_, i, AS_PRIVATE) + || findKeyword(nextLine_, i, AS_PROTECTED)) { if (needReset) sourceIterator->peekReset(); return true; } - string name = getCurrentWord(nextLine, i); + string name = getCurrentWord(nextLine_, i); i += name.length() - 1; } } // end of for loop @@ -4443,7 +4530,7 @@ * @param index the current line index. * @return true if the statement is EXEC SQL. */ -bool ASFormatter::isExecSQL(string &line, size_t index) const +bool ASFormatter::isExecSQL(string& line, size_t index) const { if (line[index] != 'e' && line[index] != 'E') // quick check to reject most return false; @@ -4488,7 +4575,8 @@ { if (!isWhiteSpace(currentLine[i])) // don't delete any text { - i = 0; + if (i < continuationIncrementIn) + leadingSpaces = i + tabIncrementIn; continuationIncrementIn = tabIncrementIn; break; } @@ -4509,6 +4597,8 @@ newLine.append(currentLine, i, len-i); currentLine = newLine; charNum = leadingChars; + if (currentLine.length() == 0) + currentLine = string(" "); // a null is inserted if this is not done } if (i >= len) charNum = 0; @@ -4516,5 +4606,151 @@ return; } +/** + * Determine if a header is a closing header + * + * @return true if the header is a closing header. + */ +bool ASFormatter::isClosingHeader(const string* header) const +{ + return (header == &AS_ELSE + || header == &AS_CATCH + || header == &AS_FINALLY); +} + +/** + * Determine if a < is a template definition or instantiation. + * Sets the class variables isInTemplate and templateDepth. + */ +void ASFormatter::checkIfTemplateOpener() +{ + assert(!isInTemplate && currentChar == '<'); + + int parenDepth_ = 0; + int maxTemplateDepth = 0; + templateDepth = 0; + for (size_t i = charNum; i < currentLine.length(); i++) + { + char currentChar_ = currentLine[i]; + + if (isWhiteSpace(currentChar_)) + continue; + + if (currentChar_ == '<') + { + templateDepth++; + maxTemplateDepth++; + } + else if (currentChar_ == '>') + { + templateDepth--; + if (templateDepth == 0) + { + if (parenDepth_ == 0) + { + // this is a template! + isInTemplate = true; + templateDepth = maxTemplateDepth; + } + return; + } + } + else if (currentChar_ == '(' || currentChar_ == ')') + { + if (currentChar_ == '(') + parenDepth_++; + else + parenDepth_--; + continue; + } + else if (currentLine.compare(i, 2, "&&") == 0 + || currentLine.compare(i, 2, "||") == 0) + { + // this is not a template -> leave... + isInTemplate = false; + return; + } + else if (currentChar_ == ',' // comma, e.g. A + || currentChar_ == '&' // reference, e.g. A + || currentChar_ == '*' // pointer, e.g. A + || currentChar_ == ':' // ::, e.g. std::string + || currentChar_ == '=' // assign e.g. default parameter + || currentChar_ == '[' // [] e.g. string[] + || currentChar_ == ']' // [] e.g. string[] + || currentChar_ == '(' // (...) e.g. function definition + || currentChar_ == ')') // (...) e.g. function definition + { + continue; + } + else if (!isLegalNameChar(currentChar_)) + { + // this is not a template -> leave... + isInTemplate = false; + return; + } + } +} + +/** + * Compute the input checksum. + * This is called as an assert so it for is debug config only + */ +bool ASFormatter::computeChecksumIn(const string& currentLine_) +{ + for (size_t i = 0; i < currentLine_.length(); i++) + if (!isWhiteSpace(currentLine_[i])) + checksumIn += currentLine_[i]; + return true; +} + +/** + * get the value of checksumIn for unit testing + * + * @return checksumIn. + */ +size_t ASFormatter::getChecksumIn() const +{ + return checksumIn; +} + +/** + * Compute the output checksum. + * This is called as an assert so it is for debug config only + */ +bool ASFormatter::computeChecksumOut(const string& beautifiedLine) +{ + for (size_t i = 0; i < beautifiedLine.length(); i++) + if (!isWhiteSpace(beautifiedLine[i])) + checksumOut += beautifiedLine[i]; + return true; +} + +/** + * Return isLineReady for the final check at end of file. + */ +bool ASFormatter::getIsLineReady() const +{ + return isLineReady; +} + +/** + * get the value of checksumOut for unit testing + * + * @return checksumOut. + */ +size_t ASFormatter::getChecksumOut() const +{ + return checksumOut; +} + +/** + * Return the difference in checksums. + * If zero all is okay. + */ +int ASFormatter::getChecksumDiff() const +{ + return checksumOut - checksumIn; +} + } // end namespace astyle diff -Nru astyle-1.24/src/ASResource.cpp astyle-2.01/src/ASResource.cpp --- astyle-1.24/src/ASResource.cpp 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/ASResource.cpp 2010-11-29 17:28:18.000000000 +0000 @@ -39,6 +39,7 @@ const string ASResource::AS_CASE = string("case"); const string ASResource::AS_DEFAULT = string("default"); const string ASResource::AS_CLASS = string("class"); +const string ASResource::AS_VOLATILE = string("volatile"); const string ASResource::AS_STRUCT = string("struct"); const string ASResource::AS_UNION = string("union"); const string ASResource::AS_INTERFACE = string("interface"); @@ -114,8 +115,6 @@ const string ASResource::AS_AND = string("&&"); const string ASResource::AS_OR = string("||"); const string ASResource::AS_COLON_COLON = string("::"); -const string ASResource::AS_PAREN_PAREN = string("()"); -const string ASResource::AS_BLPAREN_BLPAREN = string("[]"); const string ASResource::AS_PLUS = string("+"); const string ASResource::AS_MINUS = string("-"); @@ -158,7 +157,7 @@ * * @params the string pointers to be compared. */ -bool sortOnLength(const string *a, const string *b) +bool sortOnLength(const string* a, const string* b) { return (*a).length() > (*b).length(); } @@ -169,7 +168,7 @@ * * @params the string pointers to be compared. */ -bool sortOnName(const string *a, const string *b) +bool sortOnName(const string* a, const string* b) { return *a < *b; } @@ -262,6 +261,7 @@ { headers->push_back(&AS_CONST); headers->push_back(&AS_TEMPLATE); + headers->push_back(&AS_VOLATILE); } if (fileType == JAVA_TYPE) @@ -309,6 +309,7 @@ nonAssignmentOperators->push_back(&AS_ARROW); nonAssignmentOperators->push_back(&AS_AND); nonAssignmentOperators->push_back(&AS_OR); + nonAssignmentOperators->push_back(&AS_EQUAL_GR); sort(nonAssignmentOperators->begin(), nonAssignmentOperators->end(), sortOnLength); } @@ -349,6 +350,7 @@ { nonParenHeaders->push_back(&AS_CONST); nonParenHeaders->push_back(&AS_TEMPLATE); + nonParenHeaders->push_back(&AS_VOLATILE); } if (fileType == JAVA_TYPE) { @@ -507,7 +509,7 @@ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // check if a specific line position contains a keyword. -bool ASBase::findKeyword(const string &line, int i, const string &keyword) const +bool ASBase::findKeyword(const string& line, int i, const string& keyword) const { assert(isCharPotentialHeader(line, i)); // check the word diff -Nru astyle-1.24/src/astyle.h astyle-2.01/src/astyle.h --- astyle-1.24/src/astyle.h 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/astyle.h 2010-11-29 17:28:18.000000000 +0000 @@ -58,7 +58,7 @@ #ifdef __INTEL_COMPILER #pragma warning(disable: 383) // value copied to temporary, reference to temporary used -#pragma warning(disable: 444) // destructor for base class is not virtual +// #pragma warning(disable: 444) // destructor for base class is not virtual #pragma warning(disable: 981) // operands are evaluated in unspecified order #endif @@ -72,17 +72,17 @@ /* The enums below are not recognized by 'vectors' in Microsoft Visual C++ V5 when they are part of a namespace!!! Use Visual C++ V6 or higher. */ -enum FormatStyle { STYLE_NONE, - STYLE_ALLMAN, - STYLE_JAVA, - STYLE_KandR, - STYLE_STROUSTRUP, - STYLE_WHITESMITH, - STYLE_BANNER, - STYLE_GNU, - STYLE_LINUX, - STYLE_HORSTMANN, - STYLE_1TBS +enum FormatStyle { STYLE_NONE = 0, + STYLE_ALLMAN = 1, + STYLE_JAVA = 2, + STYLE_KR = 3, + STYLE_STROUSTRUP = 4, + STYLE_WHITESMITH = 5, + STYLE_BANNER = 6, + STYLE_GNU = 7, + STYLE_LINUX = 8, + STYLE_HORSTMANN = 9, + STYLE_1TBS = 10 }; enum BracketMode { NONE_MODE, @@ -107,12 +107,19 @@ SINGLE_LINE_TYPE = 512 }; -enum PointerAlign { ALIGN_NONE, - ALIGN_TYPE, - ALIGN_MIDDLE, - ALIGN_NAME +enum PointerAlign { ALIGN_NONE = 0, + ALIGN_TYPE = 1, + ALIGN_MIDDLE = 2, + ALIGN_NAME = 3 }; +enum MinConditional { MINCOND_ZERO = 0, + MINCOND_ONE = 1, + MINCOND_TWO = 2, + MINCOND_ONEHALF = 3, + MINCOND_END + }; + enum FileEncoding { ENCODING_OK, UTF_16BE, UTF_16LE, @@ -130,13 +137,13 @@ }; -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASSourceIterator // A pure virtual class is used by ASFormatter and ASBeautifier instead of // ASStreamIterator. This allows programs using AStyle as a plugin to define // their own ASStreamIterator. The ASStreamIterator class must inherit // this class. -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASSourceIterator { @@ -149,13 +156,15 @@ virtual void peekReset() = 0; }; -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASResource -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASResource { public: + ASResource() {} + virtual ~ASResource() {} void buildAssignmentOperators(vector* assignmentOperators); void buildCastOperators(vector* castOperators); void buildHeaders(vector* headers, int fileType, bool beautifier=false); @@ -176,8 +185,8 @@ static const string AS_PUBLIC, AS_PROTECTED, AS_PRIVATE; static const string AS_CLASS, AS_STRUCT, AS_UNION, AS_INTERFACE, AS_NAMESPACE; static const string AS_EXTERN, AS_ENUM; - static const string AS_STATIC, AS_CONST, AS_WHERE, AS_NEW; - static const string AS_SYNCHRONIZED; + static const string AS_STATIC, AS_CONST, AS_VOLATILE, AS_NEW; + static const string AS_WHERE, AS_SYNCHRONIZED; static const string AS_OPERATOR, AS_TEMPLATE; static const string AS_OPEN_BRACKET, AS_CLOSE_BRACKET; static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT; @@ -192,7 +201,7 @@ static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; static const string AS_QUESTION_QUESTION, AS_EQUAL_GR; static const string AS_ARROW, AS_AND, AS_OR; - static const string AS_COLON_COLON, AS_PAREN_PAREN, AS_BLPAREN_BLPAREN; + static const string AS_COLON_COLON; static const string AS_PLUS, AS_MINUS, AS_MULT, AS_DIV, AS_MOD, AS_GR, AS_LS; static const string AS_NOT, AS_BIT_XOR, AS_BIT_OR, AS_BIT_AND, AS_BIT_NOT; static const string AS_QUESTION, AS_COLON, AS_SEMICOLON, AS_COMMA; @@ -203,9 +212,9 @@ static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; }; // Class ASResource -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASBase -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASBase { @@ -214,11 +223,11 @@ int baseFileType; // a value from enum FileType protected: - ASBase() { baseFileType = C_TYPE; } - ~ASBase() {} + ASBase() : baseFileType(C_TYPE) { } + virtual ~ASBase() {} // functions definitions are at the end of ASResource.cpp - bool findKeyword(const string &line, int i, const string &keyword) const; + bool findKeyword(const string& line, int i, const string& keyword) const; string getCurrentWord(const string& line, size_t index) const; protected: @@ -239,7 +248,7 @@ } // check if a specific character can be part of a header - bool isCharPotentialHeader(const string &line, size_t i) const { + bool isCharPotentialHeader(const string& line, size_t i) const { assert(!isWhiteSpace(line[i])); char prevCh = ' '; if (i > 0) prevCh = line[i-1]; @@ -265,7 +274,7 @@ bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } // peek at the next unread character. - char peekNextChar(const string &line, int i) const { + char peekNextChar(const string& line, int i) const { char ch = ' '; size_t peekNum = line.find_first_not_of(" \t", i + 1); if (peekNum == string::npos) @@ -275,9 +284,9 @@ } }; // Class ASBase -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASBeautifier -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASBeautifier : protected ASResource, protected ASBase { @@ -286,17 +295,15 @@ virtual ~ASBeautifier(); virtual void init(ASSourceIterator* iter); void init(); - virtual bool hasMoreLines() const; - virtual string nextLine(); - virtual string beautify(const string &line); + virtual string beautify(const string& line); void deleteVector(vector*& container); void initVector(vector*& container); void setTabIndentation(int length = 4, bool forceTabs = false); void setSpaceIndentation(int length = 4); void setMaxInStatementIndentLength(int max); - void setMinConditionalIndentLength(int min); + void setMinConditionalIndentOption(int min); + void setMinConditionalIndentLength(); void setIndentManuallySet(bool state); - void setMinConditionalManuallySet(bool state); void setModeManuallySet(bool state); void setClassIndent(bool state); void setSwitchIndent(bool state); @@ -313,6 +320,7 @@ int getFileType(); int getIndentLength(void); string getIndentString(void); + string getNextWord(const string& line, size_t currPos) const; bool getBracketIndent(void); bool getBlockIndent(void); bool getCaseIndent(void); @@ -320,19 +328,19 @@ bool getEmptyLineFill(void); bool getForceTabIndentation(void); bool getIndentManuallySet(void); - bool getMinConditionalManuallySet(void); bool getModeManuallySet(void); + bool getPreprocessorIndent(void); bool getSwitchIndent(void); protected: void deleteStaticVectors(); - const string* findHeader(const string &line, int i, + const string* findHeader(const string& line, int i, const vector* possibleHeaders) const; - const string* findOperator(const string &line, int i, + const string* findOperator(const string& line, int i, const vector* possibleOperators) const; - int getNextProgramCharDistance(const string &line, int i) const; - int indexOf(vector &container, const string *element); - string trim(const string &str); + int getNextProgramCharDistance(const string& line, int i) const; + int indexOf(vector &container, const string* element); + string trim(const string& str); // variables set by ASFormatter - must be updated in activeBeautifierStack int inLineNumber; @@ -347,11 +355,11 @@ bool isInIndentableStruct; private: - ASBeautifier(const ASBeautifier ©); + ASBeautifier(const ASBeautifier& copy); ASBeautifier& operator=(ASBeautifier&); // not to be implemented void initStatic(); - void registerInStatementIndent(const string &line, int i, int spaceTabCount, + void registerInStatementIndent(const string& line, int i, int spaceTabCount, int tabIncrementIn, int minIndent, bool updateParenStack); string preLineWS(int spaceTabCount, int tabCount); @@ -363,7 +371,7 @@ static vector* nonAssignmentOperators; static vector* indentableHeaders; - ASSourceIterator *sourceIterator; + ASSourceIterator* sourceIterator; vector *waitingBeautifierStack; vector *activeBeautifierStack; vector *waitingBeautifierStackLengthStack; @@ -381,18 +389,19 @@ int getInStatementIndentAssign(const string& line, size_t currPos) const; int getInStatementIndentComma(const string& line, size_t currPos) const; bool isClassAccessModifier(string& line) const; + bool isIndentedPreprocessor(const string& line, size_t currPos) const; bool isLineEndComment(string& line, int startPos) const; - bool statementEndsWithComma(string &line, int index); - vector*>* copyTempStacks(const ASBeautifier &other) const; - template void deleteContainer(T &container); + bool statementEndsWithComma(string& line, int index); + vector*>* copyTempStacks(const ASBeautifier& other) const; + template void deleteContainer(T& container); void deleteContainer(vector*>* &container); - template void initContainer(T &container, T value); + template void initContainer(T& container, T value); private: // variables string indentString; - const string *currentHeader; - const string *previousLastLineHeader; - const string *probationHeader; + const string* currentHeader; + const string* previousLastLineHeader; + const string* probationHeader; bool isInQuote; bool isInVerbatimQuote; bool haveLineContinuationChar; @@ -431,6 +440,7 @@ bool blockCommentNoBeautify; bool previousLineProbationTab; int fileType; + int minConditionalOption; int minConditionalIndent; int parenDepth; int indentLength; @@ -448,23 +458,24 @@ char prevNonLegalCh; }; // Class ASBeautifier -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASEnhancer -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASEnhancer : protected ASBase { public: // functions ASEnhancer(); - ~ASEnhancer(); - void init(int, int, string, bool, bool); - void enhance(string &line, bool isInSQL); + virtual ~ASEnhancer(); + void init(int, int, string, bool, bool, bool); + void enhance(string& line, bool isInPreprocessor, bool isInSQL); private: // options from command line or options file int indentLength; bool useTabs; bool caseIndent; + bool preprocessorIndent; bool emptyLineFill; // parsing variables @@ -488,7 +499,7 @@ }; switchVariables sw; // switch variables struct - vector swVector; // stack vector of switch variables + vector switchStack; // stack vector of switch variables // event table variables bool nextLineIsEventIndent; // begin event table indent is reached @@ -500,17 +511,17 @@ private: // functions - size_t findCaseColon(string &line, size_t caseIndex) const; - int indentLine(string &line, int indent) const; - bool isBeginDeclareSectionSQL(string &line, size_t index) const; - bool isEndDeclareSectionSQL(string &line, size_t index) const; - size_t processSwitchBlock(string &line, size_t index); - int unindentLine(string &line, int unindent) const; + size_t findCaseColon(string& line, size_t caseIndex) const; + int indentLine(string& line, int indent) const; + bool isBeginDeclareSectionSQL(string& line, size_t index) const; + bool isEndDeclareSectionSQL(string& line, size_t index) const; + size_t processSwitchBlock(string& line, size_t index); + int unindentLine(string& line, int unindent) const; }; // Class ASEnhancer -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Class ASFormatter -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- class ASFormatter : public ASBeautifier { @@ -521,6 +532,7 @@ virtual bool hasMoreLines() const; virtual string nextLine(); LineEndFormat getLineEndFormat() const; + bool getIsLineReady() const; void setFormattingStyle(FormatStyle style); void setAddBracketsMode(bool state); void setAddOneLineBracketsMode(bool state); @@ -541,16 +553,19 @@ void setPointerAlignment(PointerAlign alignment); void setSingleStatementsMode(bool state); void setTabSpaceConversionMode(bool state); + size_t getChecksumIn() const; + size_t getChecksumOut() const; + int getChecksumDiff() const; private: // functions - void ASformatter(ASFormatter ©); // not to be imlpemented - ASFormatter& operator=(ASFormatter&); // not to be implemented - template void deleteContainer(T &container); - template void initContainer(T &container, T value); + ASFormatter(const ASFormatter& copy); // copy constructor not to be imlpemented + ASFormatter& operator=(ASFormatter&); // assignment operator not to be implemented + template void deleteContainer(T& container); + template void initContainer(T& container, T value); char peekNextChar() const; BracketType getBracketType(); bool addBracketsToStatement(); - bool commentAndHeaderFollows() const; + bool commentAndHeaderFollows(); bool getNextChar(); bool getNextLine(bool emptyLineWasDeleted = false); bool isBeforeComment() const; @@ -558,30 +573,32 @@ bool isBeforeAnyLineEndComment(int startPos) const; bool isBeforeMultipleLineEndComments(int startPos) const; bool isBracketType(BracketType a, BracketType b) const; + bool isClosingHeader(const string* header) const; bool isCurrentBracketBroken() const; bool isDereferenceOrAddressOf() const; - bool isExecSQL(string &line, size_t index) const; - bool isEmptyLine(const string &line) const; + bool isExecSQL(string& line, size_t index) const; + bool isEmptyLine(const string& line) const; bool isNextWordSharpNonParenHeader(int startChar) const; bool isNonInStatementArrayBracket() const; bool isPointerOrReference() const; bool isPointerOrReferenceCentered() const; bool isSharpStyleWithParen(const string* header) const; - bool isStructAccessModified(string &firstLine, size_t index) const; + bool isStructAccessModified(string& firstLine, size_t index) const; bool isUnaryOperator() const; bool isInExponent() const; - bool isOneLineBlockReached(string& line, int startChar) const; bool isNextCharOpeningBracket(int startChar) const; bool isOkToBreakBlock(BracketType bracketType) const; + int isOneLineBlockReached(string& line, int startChar) const; int getCurrentLineCommentAdjustment(); int getNextLineCommentAdjustment(); void appendCharInsideComments(); - void appendSequence(const string &sequence, bool canBreakLine = true); + void appendSequence(const string& sequence, bool canBreakLine = true); void appendSpacePad(); void appendSpaceAfter(); void breakLine(); void buildLanguageVectors(); - void checkForFollowingHeader(const string& firstLine); + void checkForHeaderFollowingComment(const string& firstLine); + void checkIfTemplateOpener(); void convertTabToSpaces(); void deleteContainer(vector* &container); void formatArrayRunIn(); @@ -589,7 +606,7 @@ void goForward(int i); void initContainer(vector* &container, vector* value); void initNewLine(); - void padOperators(const string *newOperator); + void padOperators(const string* newOperator); void padParens(); void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); void formatClosingBracket(BracketType bracketType); @@ -610,7 +627,7 @@ void trimContinuationLine(); size_t findNextChar(string& line, char searchChar, int searchStart = 0); string getPreviousWord(const string& line, int currPos) const; - string peekNextText(const string& firstLine, bool endOnEmptyLine=false) const; + string peekNextText(const string& firstLine, bool endOnEmptyLine=false, bool shouldReset=false) const; private: // variables static int formatterFileType; @@ -622,8 +639,8 @@ static vector* assignmentOperators; static vector* castOperators; - ASSourceIterator *sourceIterator; - ASEnhancer *enhancer; + ASSourceIterator* sourceIterator; + ASEnhancer* enhancer; vector *preBracketHeaderStack; vector *bracketTypeStack; @@ -632,8 +649,8 @@ string readyFormattedLine; string currentLine; string formattedLine; - const string *currentHeader; - const string *previousOperator; // used ONLY by pad-oper + const string* currentHeader; + const string* previousOperator; // used ONLY by pad-oper char currentChar; char previousChar; char previousNonWSChar; @@ -647,6 +664,8 @@ int templateDepth; int traceLineNumber; int horstmannIndentChars; + size_t checksumIn; + size_t checksumOut; size_t leadingSpaces; size_t formattedLineCommentNum; // comment location on formattedLine size_t currentLineFirstBracketNum; // first bracket location on currentLine @@ -656,6 +675,8 @@ BracketType previousBracketType; PointerAlign pointerAlignment; LineEndFormat lineEnd; + bool computeChecksumIn(const string& currentLine_); + bool computeChecksumOut(const string& beautifiedLine); bool isVirgin; bool shouldPadOperators; bool shouldPadParensOutside; @@ -668,6 +689,7 @@ bool isInComment; bool noTrimCommentContinuation; bool isInPreprocessor; + bool isInPreprocessorBeautify; bool isInTemplate; bool doesLineStartComment; bool lineEndsInCommentOnly; @@ -679,7 +701,7 @@ bool isInVerbatimQuote; bool haveLineContinuationChar; bool isInQuoteContinuation; - bool isInBlParen; +// bool isInBlParen; bool isSpecialChar; bool isNonParenHeader; bool foundQuestionMark; @@ -708,6 +730,7 @@ bool isCharImmediatelyPostTemplate; bool isCharImmediatelyPostReturn; bool isCharImmediatelyPostOperator; + bool isCharImmediatelyPostPointerOrReference; bool breakCurrentOneLineBlock; bool isInHorstmannRunIn; bool currentLineBeginsWithBracket; @@ -723,13 +746,15 @@ bool shouldBreakLineAtNextChar; bool passedSemicolon; bool passedColon; - bool clearNonInStatement; + bool isImmediatelyPostNonInStmt; + bool isCharImmediatelyPostNonInStmt; bool isImmediatelyPostComment; bool isImmediatelyPostLineComment; bool isImmediatelyPostEmptyBlock; bool isImmediatelyPostPreprocessor; bool isImmediatelyPostReturn; bool isImmediatelyPostOperator; + bool isImmediatelyPostPointerOrReference; bool shouldBreakBlocks; bool shouldBreakClosingHeaderBlocks; @@ -760,41 +785,41 @@ } // check if a specific sequence exists in the current placement of the current line - bool isSequenceReached(const char *sequence) const { + bool isSequenceReached(const char* sequence) const { return currentLine.compare(charNum, strlen(sequence), sequence) == 0; } // call ASBase::findHeader for the current character - const string *findHeader(const vector* headers) { - return ASBeautifier::findHeader(currentLine, charNum, headers); + const string* findHeader(const vector* headers_) { + return ASBeautifier::findHeader(currentLine, charNum, headers_); } // call ASBase::findOperator for the current character - const string *findOperator(const vector* headers) { - return ASBeautifier::findOperator(currentLine, charNum, headers); + const string* findOperator(const vector* headers_) { + return ASBeautifier::findOperator(currentLine, charNum, headers_); } }; // Class ASFormatter -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // astyle namespace global declarations -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // sort comparison functions for ASResource -bool sortOnLength(const string *a, const string *b); -bool sortOnName(const string *a, const string *b); +bool sortOnLength(const string* a, const string* b); +bool sortOnName(const string* a, const string* b); } // end of astyle namespace // end of astyle namespace -------------------------------------------------- -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // declarations for library build // global because they are called externally and are NOT part of the namespace -//---------------------------------------------------------------------------- +//----------------------------------------------------------------------------- -typedef void (STDCALL *fpError)(int, char*); // pointer to callback error handler -typedef char* (STDCALL *fpAlloc)(unsigned long); // pointer to callback memory allocation +typedef void (STDCALL* fpError)(int, const char*); // pointer to callback error handler +typedef char* (STDCALL* fpAlloc)(unsigned long); // pointer to callback memory allocation extern "C" EXPORT char* STDCALL AStyleMain(const char*, const char*, fpError, fpAlloc); extern "C" EXPORT const char* STDCALL AStyleGetVersion (void); diff -Nru astyle-1.24/src/astyle_main.cpp astyle-2.01/src/astyle_main.cpp --- astyle-1.24/src/astyle_main.cpp 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/astyle_main.cpp 2010-11-29 17:28:18.000000000 +0000 @@ -32,6 +32,7 @@ #include #include #include +#include // needed by some compilers (digital mars) // includes for recursive getFileNames() function #ifdef _WIN32 @@ -52,17 +53,13 @@ // turn off MinGW automatic file globbing // this CANNOT be in the astyle namespace +#ifndef ASTYLE_LIB int _CRT_glob = 0; +#endif namespace astyle { -#define IS_OPTION(arg,op) ((arg).compare(op)==0) -#define IS_OPTIONS(arg,a,b) (IS_OPTION((arg),(a)) || IS_OPTION((arg),(b))) - -#define GET_PARAM(arg,op) ((arg).substr(strlen(op))) -#define GET_PARAMS(arg,a,b) (isParamOption((arg),(a)) ? GET_PARAM((arg),(a)) : GET_PARAM((arg),(b))) - #ifdef _WIN32 char g_fileSeparator = '\\'; bool g_isCaseSensitive = false; @@ -71,11 +68,8 @@ bool g_isCaseSensitive = true; #endif -#ifdef ASTYLE_LIB -// library build variables -stringstream* _err = NULL; -#else // console build variables +#ifndef ASTYLE_LIB ostream* _err = &cerr; // direct error messages to cerr ASConsole* g_console = NULL; // class to encapsulate console variables #endif @@ -87,1295 +81,842 @@ jmethodID g_mid; #endif -const char* _version = "1.24"; +const char* g_version = "2.01"; + +//----------------------------------------------------------------------------- +// ASStreamIterator class +// typename will be istringstream for GUI and istream otherwise +//----------------------------------------------------------------------------- + +template +ASStreamIterator::ASStreamIterator(T* in) +{ + inStream = in; + buffer.reserve(200); + eolWindows = 0; + eolLinux = 0; + eolMacOld = 0; + outputEOL[0] = '\0'; + peekStart = 0; + prevLineDeleted = false; + checkForEmptyLine = false; +} +template +ASStreamIterator::~ASStreamIterator() +{ +} /** - * parse the options vector - * ITER can be either a fileOptionsVector (options file) or an optionsVector (command line) + * read the input stream, delete any end of line characters, + * and build a string that contains the input line. * - * @return true if no errors, false if errors + * @return string containing the next input line minus any end of line characters */ -template -bool parseOptions(ASFormatter &formatter, - const ITER &optionsBegin, - const ITER &optionsEnd, - const string &errorInfo) +template +string ASStreamIterator::nextLine(bool emptyLineWasDeleted) { - ITER option; - bool ok = true; - string arg, subArg; + // verify that the current position is correct + assert (peekStart == 0); - for (option = optionsBegin; option != optionsEnd; ++option) + // a deleted line may be replaced if break-blocks is requested + // this sets up the compare to check for a replaced empty line + if (prevLineDeleted) { - arg = *option; + prevLineDeleted = false; + checkForEmptyLine = true; + } + if (!emptyLineWasDeleted) + prevBuffer = buffer; + else + prevLineDeleted = true; - if (arg.compare(0, 2, "--") == 0) - ok &= parseOption(formatter, arg.substr(2), errorInfo); - else if (arg[0] == '-') - { - size_t i; + // read the next record + buffer.clear(); + char ch; + inStream->get(ch); - for (i = 1; i < arg.length(); ++i) + while (!inStream->eof() && ch != '\n' && ch != '\r') + { + buffer.append(1, ch); + inStream->get(ch); + } + + if (inStream->eof()) + { + return buffer; + } + + int peekCh = inStream->peek(); + + // find input end-of-line characters + if (!inStream->eof()) + { + if (ch == '\r') // CR+LF is windows otherwise Mac OS 9 + { + if (peekCh == '\n') { - if (isalpha(arg[i]) && i > 1) - { - ok &= parseOption(formatter, subArg, errorInfo); - subArg = ""; - } - subArg.append(1, arg[i]); + inStream->get(); + eolWindows++; } - ok &= parseOption(formatter, subArg, errorInfo); - subArg = ""; + else + eolMacOld++; } - else + else // LF is Linux, allow for improbable LF/CR { - ok &= parseOption(formatter, arg, errorInfo); - subArg = ""; + if (peekCh == '\r') + { + inStream->get(); + eolWindows++; + } + else + eolLinux++; } } - return ok; + else + { + inStream->clear(); + } + + // set output end of line characters + if (eolWindows >= eolLinux) + { + if (eolWindows >= eolMacOld) + strcpy(outputEOL, "\r\n"); // Windows (CR+LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + } + else if (eolLinux >= eolMacOld) + strcpy(outputEOL, "\n"); // Linux (LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + + return buffer; } -void importOptions(istream &in, vector &optionsVector) +// save the current position and get the next line +// this can be called for multiple reads +// when finished peeking you MUST call peekReset() +// call this function from ASFormatter ONLY +template +string ASStreamIterator::peekNextLine() { + assert (hasMoreLines()); + string nextLine_; char ch; - string currentToken; - - while (in) - { - currentToken = ""; - do - { - in.get(ch); - if (in.eof()) - break; - // treat '#' as line comments - if (ch == '#') - while (in) - { - in.get(ch); - if (ch == '\n') - break; - } - // break options on spaces, tabs, commas, or new-lines - if (in.eof() || ch == ' ' || ch == '\t' || ch == ',' || ch == '\n') - break; - else - currentToken.append(1, ch); + if (peekStart == 0) + peekStart = inStream->tellg(); - } - while (in); + // read the next record + inStream->get(ch); + while (!inStream->eof() && ch != '\n' && ch != '\r') + { + nextLine_.append(1, ch); + inStream->get(ch); + } - if (currentToken.length() != 0) - optionsVector.push_back(currentToken); + if (inStream->eof()) + { + return nextLine_; } -} -void isOptionError(const string &arg, const string &errorInfo) -{ -#ifdef ASTYLE_LIB - if (_err->str().length() == 0) + int peekCh = inStream->peek(); + + // remove end-of-line characters + if (!inStream->eof()) { - (*_err) << errorInfo << endl; // need main error message - (*_err) << arg; // output the option in error + if ((peekCh == '\n' || peekCh == '\r') && peekCh != ch) ///////////// changed ////////// + inStream->get(); } - else - (*_err) << endl << arg; // put endl after previous option -#else - if (errorInfo.length() > 0) // to avoid a compiler warning - g_console->error("Error in param: ", arg.c_str()); -#endif -} + return nextLine_; +} -bool isParamOption(const string &arg, const char *option) +// reset current position and EOF for peekNextLine() +template +void ASStreamIterator::peekReset() { - bool retVal = arg.compare(0, strlen(option), option) == 0; - // if comparing for short option, 2nd char of arg must be numeric - if (retVal && strlen(option) == 1 && arg.length() > 1) - if (!isdigit(arg[1])) - retVal = false; - return retVal; + assert(peekStart != 0); + inStream->clear(); + inStream->seekg(peekStart); + peekStart = 0; } -bool isParamOption(const string &arg, const char *option1, const char *option2) +// save the last input line after input has reached EOF +template +void ASStreamIterator::saveLastInputLine() { - return isParamOption(arg, option1) || isParamOption(arg, option2); + assert(inStream->eof()); + prevBuffer = buffer; } -bool parseOption(ASFormatter &formatter, const string &arg, const string &errorInfo) +// check for a change in line ends +template +bool ASStreamIterator::getLineEndChange(int lineEndFormat) const { - if ( IS_OPTION(arg, "style=allman") || IS_OPTION(arg, "style=ansi") || IS_OPTION(arg, "style=bsd") ) - { - formatter.setFormattingStyle(STYLE_ALLMAN); - } - else if ( IS_OPTION(arg, "style=java") ) - { - formatter.setFormattingStyle(STYLE_JAVA); - } - else if ( IS_OPTION(arg, "style=k&r") || IS_OPTION(arg, "style=k/r") ) - { - formatter.setFormattingStyle(STYLE_KandR); - } - else if ( IS_OPTION(arg, "style=stroustrup") ) - { - formatter.setFormattingStyle(STYLE_STROUSTRUP); - } - else if ( IS_OPTION(arg, "style=whitesmith") ) - { - formatter.setFormattingStyle(STYLE_WHITESMITH); - } - else if ( IS_OPTION(arg, "style=banner") ) - { - formatter.setFormattingStyle(STYLE_BANNER); - } - else if ( IS_OPTION(arg, "style=gnu") ) - { - formatter.setFormattingStyle(STYLE_GNU); - } - else if ( IS_OPTION(arg, "style=linux") ) - { - formatter.setFormattingStyle(STYLE_LINUX); - } - else if ( IS_OPTION(arg, "style=horstmann") ) + assert(lineEndFormat == LINEEND_DEFAULT + || lineEndFormat == LINEEND_WINDOWS + || lineEndFormat == LINEEND_LINUX + || lineEndFormat == LINEEND_MACOLD); + + bool lineEndChange = false; + if (lineEndFormat == LINEEND_WINDOWS) + lineEndChange = (eolLinux + eolMacOld != 0); + else if (lineEndFormat == LINEEND_LINUX) + lineEndChange = (eolWindows + eolMacOld != 0); + else if (lineEndFormat == LINEEND_MACOLD) + lineEndChange = (eolWindows + eolLinux != 0); + else { - formatter.setFormattingStyle(STYLE_HORSTMANN); + if (eolWindows > 0) + lineEndChange = (eolLinux + eolMacOld != 0); + else if (eolLinux > 0) + lineEndChange = (eolWindows + eolMacOld != 0); + else if (eolMacOld > 0) + lineEndChange = (eolWindows + eolLinux != 0); } - else if ( IS_OPTION(arg, "style=1tbs") || IS_OPTION(arg, "style=otbs") ) + return lineEndChange; +} + +#ifndef ASTYLE_LIB +//----------------------------------------------------------------------------- +// ASConsole class +// main function will be included only in the console build +//----------------------------------------------------------------------------- + +// rewrite a stringstream converting the line ends +void ASConsole::convertLineEnds(ostringstream& out, int lineEnd) +{ + assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD); + const string& inStr = out.str(); // avoids strange looking syntax + string outStr; // the converted ouput + int inLength = inStr.length(); + for (int pos = 0; pos < inLength; pos++) { - formatter.setFormattingStyle(STYLE_1TBS); - } - else if ( isParamOption(arg, "A") ) - { - int style = 0; - string styleParam = GET_PARAM(arg, "A"); - if (styleParam.length() > 0) - style = atoi(styleParam.c_str()); - if (style < 1 || style > 10) - isOptionError(arg, errorInfo); - else if (style == 1) - formatter.setFormattingStyle(STYLE_ALLMAN); - else if (style == 2) - formatter.setFormattingStyle(STYLE_JAVA); - else if (style == 3) - formatter.setFormattingStyle(STYLE_KandR); - else if (style == 4) - formatter.setFormattingStyle(STYLE_STROUSTRUP); - else if (style == 5) - formatter.setFormattingStyle(STYLE_WHITESMITH); - else if (style == 6) - formatter.setFormattingStyle(STYLE_BANNER); - else if (style == 7) - formatter.setFormattingStyle(STYLE_GNU); - else if (style == 8) - formatter.setFormattingStyle(STYLE_LINUX); - else if (style == 9) - formatter.setFormattingStyle(STYLE_HORSTMANN); - else if (style == 10) - formatter.setFormattingStyle(STYLE_1TBS); - } - // must check for mode=cs before mode=c !!! - else if ( IS_OPTION(arg, "mode=cs") ) - { - formatter.setSharpStyle(); - formatter.setModeManuallySet(true); - } - else if ( IS_OPTION(arg, "mode=c") ) - { - formatter.setCStyle(); - formatter.setModeManuallySet(true); - } - else if ( IS_OPTION(arg, "mode=java") ) - { - formatter.setJavaStyle(); - formatter.setModeManuallySet(true); - } - else if ( isParamOption(arg, "t", "indent=tab=") ) - { - int spaceNum = 4; - string spaceNumParam = GET_PARAMS(arg, "t", "indent=tab="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); + if (inStr[pos] == '\r') + { + if (inStr[pos+ 1] == '\n') + { + // CRLF + if (lineEnd == LINEEND_CR) + { + outStr += inStr[pos]; // Delete the LF + pos++; + continue; + } + else if (lineEnd == LINEEND_LF) + { + outStr += inStr[pos+1]; // Delete the CR + pos++; + continue; + } + else + { + outStr += inStr[pos]; // Do not change + outStr += inStr[pos+1]; + pos++; + continue; + } + } + else + { + // CR + if (lineEnd == LINEEND_CRLF) + { + outStr += inStr[pos]; // Insert the CR + outStr += '\n'; // Insert the LF + continue; + } + else if (lineEnd == LINEEND_LF) + { + outStr += '\n'; // Insert the LF + continue; + } + else + { + outStr += inStr[pos]; // Do not change + continue; + } + } + } + else if (inStr[pos] == '\n') + { + // LF + if (lineEnd == LINEEND_CRLF) + { + outStr += '\r'; // Insert the CR + outStr += inStr[pos]; // Insert the LF + continue; + } + else if (lineEnd == LINEEND_CR) + { + outStr += '\r'; // Insert the CR + continue; + } + else + { + outStr += inStr[pos]; // Do not change + continue; + } + } else { - formatter.setTabIndentation(spaceNum, false); - formatter.setIndentManuallySet(true); + outStr += inStr[pos]; // Write the current char } } - else if ( IS_OPTION(arg, "indent=tab") ) - { - formatter.setTabIndentation(4); - // do NOT call setIndentManuallySet(true); - } - else if ( isParamOption(arg, "T", "indent=force-tab=") ) + // replace the stream + out.str(outStr); +} + +void ASConsole::correctMixedLineEnds(ostringstream& out) +{ + LineEndFormat lineEndFormat = LINEEND_DEFAULT; + if (strcmp(outputEOL, "\r\n") == 0) + lineEndFormat = LINEEND_WINDOWS; + if (strcmp(outputEOL, "\n") == 0) + lineEndFormat = LINEEND_LINUX; + if (strcmp(outputEOL, "\r") == 0) + lineEndFormat = LINEEND_MACOLD; + convertLineEnds(out, lineEndFormat); +} + +// error exit without a message +void ASConsole::error() const +{ + (*_err) << "\nArtistic Style has terminated!" << endl; + exit(EXIT_FAILURE); +} + +// error exit with a message +void ASConsole::error(const char* why, const char* what) const +{ + (*_err) << why << ' ' << what << endl; + error(); +} + +/** + * If no files have been given, use cin for input and cout for output. + * + * This is used to format text for text editors like TextWrangler (Mac). + * Do NOT display any console messages when this function is used. + */ +void ASConsole::formatCinToCout() const +{ + verifyCinPeek(); + ASStreamIterator streamIterator(&cin); // create iterator for cin + formatter.init(&streamIterator); + + while (formatter.hasMoreLines()) { - int spaceNum = 4; - string spaceNumParam = GET_PARAMS(arg, "T", "indent=force-tab="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); + cout << formatter.nextLine(); + if (formatter.hasMoreLines()) + cout << streamIterator.getOutputEOL(); else { - formatter.setTabIndentation(spaceNum, true); - formatter.setIndentManuallySet(true); + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + cout << streamIterator.getOutputEOL(); + cout << formatter.nextLine(); + } } } - else if ( IS_OPTION(arg, "indent=force-tab") ) + cout.flush(); +} + +/** + * Verify that tellg() works with cin. + * This will fail if cin is piped to AStyle "cat txt.cpp | ./astyled". + * But is OK for redirection "./astyled < txt.cpp". + */ +void ASConsole::verifyCinPeek() const +{ + streamoff currPos = cin.tellg(); + if (currPos == -1) { - formatter.setTabIndentation(4, true); - // do NOT call setIndentManuallySet(true); + (*_err) << "Cannot process the input stream." << endl; + error(); } - else if ( isParamOption(arg, "s", "indent=spaces=") ) +} + +/** + * Open input file, format it, and close the output. + * + * @param fileName_ The path and name of the file to be processed. + * @param formatter The formatter object. + */ +void ASConsole::formatFile(const string& fileName_) +{ + // open input file + ifstream in(fileName_.c_str(), ios::binary); + if (!in) + error("Cannot open input file", fileName_.c_str()); + + ostringstream out; + + // Unless a specific language mode has been set, set the language mode + // according to the file's suffix. + if (!formatter.getModeManuallySet()) { - int spaceNum = 4; - string spaceNumParam = GET_PARAMS(arg, "s", "indent=spaces="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); + if (stringEndsWith(fileName_, string(".java"))) + formatter.setJavaStyle(); + else if (stringEndsWith(fileName_, string(".cs"))) + formatter.setSharpStyle(); else - { - formatter.setSpaceIndentation(spaceNum); - formatter.setIndentManuallySet(true); - } - } - else if ( IS_OPTION(arg, "indent=spaces") ) - { - formatter.setSpaceIndentation(4); - // do NOT call setIndentManuallySet(true); + formatter.setCStyle(); } - else if ( isParamOption(arg, "m", "min-conditional-indent=") ) + + ASStreamIterator streamIterator(&in); + formatter.init(&streamIterator); + + // make sure encoding is 8 bit + // if not set the eofbit so the file is not formatted + FileEncoding encoding = getFileEncoding(in); + if (encoding != ENCODING_OK) + in.setstate(ios::eofbit); + + // set line end format + string nextLine; // next output line + filesAreIdentical = true; // input and output files are identical + LineEndFormat lineEndFormat = formatter.getLineEndFormat(); + initializeOutputEOL(lineEndFormat); + + // format the file + while (formatter.hasMoreLines()) { - int minIndent = 8; - string minIndentParam = GET_PARAMS(arg, "m", "min-conditional-indent="); - if (minIndentParam.length() > 0) - minIndent = atoi(minIndentParam.c_str()); - if (minIndent > 40) - isOptionError(arg, errorInfo); + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + if (formatter.hasMoreLines()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + } else { - formatter.setMinConditionalIndentLength(minIndent); - formatter.setMinConditionalManuallySet(true); + streamIterator.saveLastInputLine(); // to compare the last input line + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + streamIterator.saveLastInputLine(); + } + } + + if (filesAreIdentical) + { + if (streamIterator.checkForEmptyLine) + { + if (nextLine.find_first_not_of(" \t") != string::npos) + filesAreIdentical = false; + } + else if (!streamIterator.compareToInputBuffer(nextLine)) + filesAreIdentical = false; + streamIterator.checkForEmptyLine = false; } } - else if ( isParamOption(arg, "M", "max-instatement-indent=") ) + // correct for mixed line ends + if (lineEndsMixed) { - int maxIndent = 40; - string maxIndentParam = GET_PARAMS(arg, "M", "max-instatement-indent="); - if (maxIndentParam.length() > 0) - maxIndent = atoi(maxIndentParam.c_str()); - if (maxIndent > 80) - isOptionError(arg, errorInfo); - else - formatter.setMaxInStatementIndentLength(maxIndent); - } - else if ( IS_OPTIONS(arg, "B", "indent-brackets") ) - { - formatter.setBracketIndent(true); - } - else if ( IS_OPTIONS(arg, "G", "indent-blocks") ) - { - formatter.setBlockIndent(true); - } - else if ( IS_OPTIONS(arg, "N", "indent-namespaces") ) - { - formatter.setNamespaceIndent(true); - } - else if ( IS_OPTIONS(arg, "C", "indent-classes") ) - { - formatter.setClassIndent(true); - } - else if ( IS_OPTIONS(arg, "S", "indent-switches") ) - { - formatter.setSwitchIndent(true); - } - else if ( IS_OPTIONS(arg, "K", "indent-cases") ) - { - formatter.setCaseIndent(true); - } - else if ( IS_OPTIONS(arg, "L", "indent-labels") ) - { - formatter.setLabelIndent(true); - } - else if ( IS_OPTIONS(arg, "y", "break-closing-brackets") ) - { - formatter.setBreakClosingHeaderBracketsMode(true); - } - else if ( IS_OPTIONS(arg, "b", "brackets=break") ) - { - formatter.setBracketFormatMode(BREAK_MODE); - } - else if ( IS_OPTIONS(arg, "a", "brackets=attach") ) - { - formatter.setBracketFormatMode(ATTACH_MODE); - } - else if ( IS_OPTIONS(arg, "l", "brackets=linux") ) - { - formatter.setBracketFormatMode(LINUX_MODE); - } - else if ( IS_OPTIONS(arg, "u", "brackets=stroustrup") ) - { - formatter.setBracketFormatMode(STROUSTRUP_MODE); - } - else if ( IS_OPTIONS(arg, "g", "brackets=horstmann") ) - { - formatter.setBracketFormatMode(HORSTMANN_MODE); - } - else if ( IS_OPTIONS(arg, "O", "keep-one-line-blocks") ) - { - formatter.setBreakOneLineBlocksMode(false); - } - else if ( IS_OPTIONS(arg, "o", "keep-one-line-statements") ) - { - formatter.setSingleStatementsMode(false); - } - else if ( IS_OPTIONS(arg, "P", "pad-paren") ) - { - formatter.setParensOutsidePaddingMode(true); - formatter.setParensInsidePaddingMode(true); - } - else if ( IS_OPTIONS(arg, "d", "pad-paren-out") ) - { - formatter.setParensOutsidePaddingMode(true); - } - else if ( IS_OPTIONS(arg, "D", "pad-paren-in") ) - { - formatter.setParensInsidePaddingMode(true); - } - else if ( IS_OPTIONS(arg, "H", "pad-header") ) - { - formatter.setParensHeaderPaddingMode(true); - } - else if ( IS_OPTIONS(arg, "U", "unpad-paren") ) - { - formatter.setParensUnPaddingMode(true); - } - else if ( IS_OPTIONS(arg, "p", "pad-oper") ) - { - formatter.setOperatorPaddingMode(true); - } - else if ( IS_OPTIONS(arg, "x", "delete-empty-lines") ) - { - formatter.setDeleteEmptyLinesMode(true); - } - else if ( IS_OPTIONS(arg, "E", "fill-empty-lines") ) - { - formatter.setEmptyLineFill(true); - } - else if ( IS_OPTIONS(arg, "w", "indent-preprocessor") ) - { - formatter.setPreprocessorIndent(true); - } - else if ( IS_OPTIONS(arg, "c", "convert-tabs") ) - { - formatter.setTabSpaceConversionMode(true); - } - else if ( IS_OPTIONS(arg, "F", "break-blocks=all") ) - { - formatter.setBreakBlocksMode(true); - formatter.setBreakClosingHeaderBlocksMode(true); - } - else if ( IS_OPTIONS(arg, "f", "break-blocks") ) - { - formatter.setBreakBlocksMode(true); - } - else if ( IS_OPTIONS(arg, "e", "break-elseifs") ) - { - formatter.setBreakElseIfsMode(true); - } - else if ( IS_OPTIONS(arg, "j", "add-brackets") ) - { - formatter.setAddBracketsMode(true); - } - else if ( IS_OPTIONS(arg, "J", "add-one-line-brackets") ) - { - formatter.setAddOneLineBracketsMode(true); - } - else if ( IS_OPTIONS(arg, "Y", "indent-col1-comments") ) - { - formatter.setIndentCol1CommentsMode(true); - } - else if ( IS_OPTION(arg, "align-pointer=type") ) - { - formatter.setPointerAlignment(ALIGN_TYPE); - } - else if ( IS_OPTION(arg, "align-pointer=middle") ) - { - formatter.setPointerAlignment(ALIGN_MIDDLE); - } - else if ( IS_OPTION(arg, "align-pointer=name") ) - { - formatter.setPointerAlignment(ALIGN_NAME); - } - else if ( isParamOption(arg, "k") ) - { - int align = 0; - string styleParam = GET_PARAM(arg, "k"); - if (styleParam.length() > 0) - align = atoi(styleParam.c_str()); - if (align < 1 || align > 3) - isOptionError(arg, errorInfo); - else if (align == 1) - formatter.setPointerAlignment(ALIGN_TYPE); - else if (align == 2) - formatter.setPointerAlignment(ALIGN_MIDDLE); - else if (align == 3) - formatter.setPointerAlignment(ALIGN_NAME); - } - // depreciated options ///////////////////////////////////////////////////////////////////////////////////// - // depreciated in release 1.23 - // removed from documentation in release 1.24 - // may be removed at an appropriate time -// else if ( IS_OPTION(arg, "style=kr") ) -// { -// formatter.setFormattingStyle(STYLE_JAVA); -// } - else if ( isParamOption(arg, "T", "force-indent=tab=") ) - { - // the 'T' option will already have been processed - int spaceNum = 4; - string spaceNumParam = GET_PARAMS(arg, "T", "force-indent=tab="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 1 || spaceNum > 20) - isOptionError(arg, errorInfo); - else - formatter.setTabIndentation(spaceNum, true); - } - else if ( IS_OPTION(arg, "brackets=break-closing") ) - { - formatter.setBreakClosingHeaderBracketsMode(true); + correctMixedLineEnds(out); + filesAreIdentical = false; } + in.close(); - else if ( IS_OPTION(arg, "one-line=keep-blocks") ) - { - formatter.setBreakOneLineBlocksMode(false); - } - else if ( IS_OPTION(arg, "one-line=keep-statements") ) - { - formatter.setSingleStatementsMode(false); - } - else if ( IS_OPTION(arg, "pad=paren") ) - { - formatter.setParensOutsidePaddingMode(true); - formatter.setParensInsidePaddingMode(true); - } - else if ( IS_OPTION(arg, "pad=paren-out") ) - { - formatter.setParensOutsidePaddingMode(true); - } - else if ( IS_OPTION(arg, "pad=paren-in") ) - { - formatter.setParensInsidePaddingMode(true); - } - else if ( IS_OPTION(arg, "unpad=paren") ) - { - formatter.setParensUnPaddingMode(true); - } - else if ( IS_OPTION(arg, "pad=oper") ) - { - formatter.setOperatorPaddingMode(true); - } - // end depreciated options ////////////////////////////////////////////////////////////////////////////// -#ifdef ASTYLE_LIB - // End of options used by GUI + // remove targetDirectory from filename if required by print + string displayName; + if (hasWildcard) + displayName = fileName_.substr(targetDirectory.length() + 1); else - isOptionError(arg, errorInfo); -#else - // Options used by only console - else if ( IS_OPTIONS(arg, "n", "suffix=none") ) - { - g_console->setNoBackup(true); - } - else if ( isParamOption(arg, "suffix=") ) - { - string suffixParam = GET_PARAM(arg, "suffix="); - if (suffixParam.length() > 0) - { - g_console->setOrigSuffix(suffixParam); - } - } - else if ( isParamOption(arg, "exclude=") ) - { - string suffixParam = GET_PARAM(arg, "exclude="); - if (suffixParam.length() > 0) - g_console->updateExcludeVector(suffixParam); - } - else if ( IS_OPTIONS(arg, "r", "R") || IS_OPTION(arg, "recursive") ) - { - g_console->setIsRecursive(true); - } - else if ( IS_OPTIONS(arg, "Z", "preserve-date") ) - { - g_console->setPreserveDate(true); - } - else if ( IS_OPTIONS(arg, "v", "verbose") ) - { - g_console->setIsVerbose(true); - } - else if ( IS_OPTIONS(arg, "Q", "formatted") ) - { - g_console->setIsFormattedOnly(true); - } - else if ( IS_OPTIONS(arg, "q", "quiet") ) - { - g_console->setIsQuiet(true); - } - else if ( IS_OPTIONS(arg, "X", "errors-to-stdout") ) - { - _err = &cout; - } - else if ( IS_OPTION(arg, "lineend=windows") ) - { - formatter.setLineEndFormat(LINEEND_WINDOWS); - } - else if ( IS_OPTION(arg, "lineend=linux") ) - { - formatter.setLineEndFormat(LINEEND_LINUX); - } - else if ( IS_OPTION(arg, "lineend=macold") ) - { - formatter.setLineEndFormat(LINEEND_MACOLD); - } - else if ( isParamOption(arg, "z") ) + displayName = fileName_; + + // if file has changed, write the new file + if (!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) { - int lineendType = 0; - string lineendParam = GET_PARAM(arg, "z"); - if (lineendParam.length() > 0) - lineendType = atoi(lineendParam.c_str()); - if (lineendType < 1 || lineendType > 3) - isOptionError(arg, errorInfo); - else if (lineendType == 1) - formatter.setLineEndFormat(LINEEND_WINDOWS); - else if (lineendType == 2) - formatter.setLineEndFormat(LINEEND_LINUX); - else if (lineendType == 3) - formatter.setLineEndFormat(LINEEND_MACOLD); + writeOutputFile(fileName_, out); + printMsg("formatted " + displayName); + filesFormatted++; } else { - (*_err) << errorInfo << arg << endl; - return false; // invalid option + if (!isFormattedOnly || encoding != ENCODING_OK) + printMsg("unchanged* " + displayName); + filesUnchanged++; + if (encoding != ENCODING_OK) + printBadEncoding(encoding); } -#endif -// End of parseOption function - return true; //o.k. -} -//-------------------------------------------------------------------------------------- -// ASStreamIterator class -// typename will be istringstream for GUI and istream otherwise -//-------------------------------------------------------------------------------------- + assert(formatter.getChecksumDiff() == 0); +} -template -ASStreamIterator::ASStreamIterator(T *in) +// build a vector of argv options +// the program path argv[0] is excluded +vector ASConsole::getArgvOptions(int argc, char** argv) const { - inStream = in; - buffer.reserve(200); - eolWindows = 0; - eolLinux = 0; - eolMacOld = 0; - outputEOL[0] = '\0'; - peekStart = 0; - prevLineDeleted = false; - checkForEmptyLine = false; + vector argvOptions; + for (int i = 1; i < argc; i++) + { + argvOptions.push_back(string(argv[i])); + } + return argvOptions; } -template -ASStreamIterator::~ASStreamIterator() +// for unit testing +vector ASConsole::getExcludeHitsVector() { + return excludeHitsVector; } -/** - * read the input stream, delete any end of line characters, - * and build a string that contains the input line. - * - * @return string containing the next input line minus any end of line characters - */ -template -string ASStreamIterator::nextLine(bool emptyLineWasDeleted) -{ - // verify that the current position is correct - assert (peekStart == 0); +// for unit testing +vector ASConsole::getExcludeVector() +{ return excludeVector; } - // a deleted line may be replaced if break-blocks is requested - // this sets up the compare to check for a replaced empty line - if (prevLineDeleted) - { - prevLineDeleted = false; - checkForEmptyLine = true; - } - if (!emptyLineWasDeleted) - prevBuffer = buffer; - else - prevLineDeleted = true; +// for unit testing +vector ASConsole::getFileName() +{ return fileName; } - // read the next record - buffer.clear(); - char ch; - inStream->get(ch); +// for unit testing +vector ASConsole::getFileNameVector() +{ return fileNameVector; } - while (!inStream->eof() && ch != '\n' && ch != '\r') - { - buffer.append(1, ch); - inStream->get(ch); - } +// for unit testing +vector ASConsole::getFileOptionsVector() +{ return fileOptionsVector; } - if (inStream->eof()) - { - return buffer; - } +int ASConsole::getFilesUnchanged() +{ return filesUnchanged; } - int peekCh = inStream->peek(); +int ASConsole::getFilesFormatted() +{ return filesFormatted; } - // find input end-of-line characters - if (!inStream->eof()) - { - if (ch == '\r') // CR+LF is windows otherwise Mac OS 9 - { - if (peekCh == '\n') - { - inStream->get(); - eolWindows++; - } - else - eolMacOld++; - } - else // LF is Linux, allow for improbable LF/CR - { - if (peekCh == '\r') - { - inStream->get(); - eolWindows++; - } - else - eolLinux++; - } - } - else - { - inStream->clear(); - } +bool ASConsole::getIsFormattedOnly() +{ return isFormattedOnly; } - // set output end of line characters - if (eolWindows >= eolLinux) - { - if (eolWindows >= eolMacOld) - strcpy(outputEOL, "\r\n"); // Windows (CR+LF) - else - strcpy(outputEOL, "\r"); // MacOld (CR) - } - else if (eolLinux >= eolMacOld) - strcpy(outputEOL, "\n"); // Linux (LF) - else - strcpy(outputEOL, "\r"); // MacOld (CR) +bool ASConsole::getIsQuiet() +{ return isQuiet; } - return buffer; -} +bool ASConsole::getIsRecursive() +{ return isRecursive; } -// save the current position and get the next line -// this can be called for multiple reads -// when finished peeking you MUST call peekReset() -// call this function from ASFormatter ONLY -template -string ASStreamIterator::peekNextLine() -{ - assert (hasMoreLines()); - string nextLine; - char ch; +bool ASConsole::getIsVerbose() +{ return isVerbose; } - if (peekStart == 0) - peekStart = inStream->tellg(); +bool ASConsole::getLineEndsMixed() +{ return lineEndsMixed; } - // read the next record - inStream->get(ch); - while (!inStream->eof() && ch != '\n' && ch != '\r') - { - nextLine.append(1, ch); - inStream->get(ch); - } +bool ASConsole::getNoBackup() +{ return noBackup; } - if (inStream->eof()) - { - return nextLine; - } +string ASConsole::getOptionsFileName() +{ return optionsFileName; } - int peekCh = inStream->peek(); +bool ASConsole::getOptionsFileRequired() +{ return optionsFileRequired; } - // remove end-of-line characters - if (!inStream->eof()) - { - if ((peekCh == '\n' || peekCh == '\r') && peekCh != ch) ///////////// changed ////////// - inStream->get(); - } +// for unit testing +vector ASConsole::getOptionsVector() +{ return optionsVector; } - return nextLine; -} +string ASConsole::getOrigSuffix() +{ return origSuffix; } -// reset current position and EOF for peekNextLine() -template -void ASStreamIterator::peekReset() +string ASConsole::getParam(const string& arg, const char* op) { - assert(peekStart != 0); - inStream->clear(); - inStream->seekg(peekStart); - peekStart = 0; + return arg.substr(strlen(op)); } -// save the last input line after input has reached EOF -template -void ASStreamIterator::saveLastInputLine() -{ - assert(inStream->eof()); - prevBuffer = buffer; -} +bool ASConsole::getPreserveDate() +{ return preserveDate; } -// check for a change in line ends -template -bool ASStreamIterator::getLineEndChange(int lineEndFormat) const +// initialize output end of line +void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat) { assert(lineEndFormat == LINEEND_DEFAULT || lineEndFormat == LINEEND_WINDOWS || lineEndFormat == LINEEND_LINUX || lineEndFormat == LINEEND_MACOLD); - bool lineEndChange = false; + outputEOL[0] = '\0'; // current line end + prevEOL[0] = '\0'; // previous line end + lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only + if (lineEndFormat == LINEEND_WINDOWS) - lineEndChange = (eolLinux + eolMacOld != 0); + strcpy(outputEOL, "\r\n"); else if (lineEndFormat == LINEEND_LINUX) - lineEndChange = (eolWindows + eolMacOld != 0); + strcpy(outputEOL, "\n"); else if (lineEndFormat == LINEEND_MACOLD) - lineEndChange = (eolWindows + eolLinux != 0); + strcpy(outputEOL, "\r"); else - { - if (eolWindows > 0) - lineEndChange = (eolLinux + eolMacOld != 0); - else if (eolLinux > 0) - lineEndChange = (eolWindows + eolMacOld != 0); - else if (eolMacOld > 0) - lineEndChange = (eolWindows + eolLinux != 0); - } - return lineEndChange; + outputEOL[0] = '\0'; } -#ifndef ASTYLE_LIB -//-------------------------------------------------------------------------------------- -// ASConsole class -// main function will be included only in the console build -//-------------------------------------------------------------------------------------- +void ASConsole::printBadEncoding(FileEncoding encoding) const +{ + string msg = "********** previous file: "; + if (encoding == UTF_16BE) + msg += "UTF-16BE encoding"; + else if (encoding == UTF_16LE) + msg += "UTF-16LE encoding"; + else if (encoding == UTF_32BE) + msg += "UTF-32BE encoding"; + else if (encoding == UTF_32LE) + msg += "UTF-32LE encoding"; + else + msg += "???????? encoding"; + printMsg(msg); +} -// rewrite a stringstream converting the line ends -void ASConsole::convertLineEnds(ostringstream& out, int lineEnd) +void ASConsole::setIsFormattedOnly(bool state) +{ isFormattedOnly = state; } + +void ASConsole::setIsQuiet(bool state) +{ isQuiet = state; } + +void ASConsole::setIsRecursive(bool state) +{ isRecursive = state; } + +void ASConsole::setIsVerbose(bool state) +{ isVerbose = state; } + +void ASConsole::setNoBackup(bool state) +{ noBackup = state; } + +void ASConsole::setOptionsFileName(string name) +{ optionsFileName = name; } + +void ASConsole::setOptionsFileRequired(bool state) +{ optionsFileRequired = state; } + +void ASConsole::setOrigSuffix(string suffix) +{ origSuffix = suffix; } + +void ASConsole::setPreserveDate(bool state) +{ preserveDate = state; } + +// set outputEOL variable +void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL) { - assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD); - const string& inStr = out.str(); // avoids strange looking syntax - string outStr; // the converted ouput - int inLength = inStr.length(); - for (int pos = 0; pos < inLength; pos++) + if (lineEndFormat == LINEEND_DEFAULT) { - if (inStr[pos] == '\r') + strcpy(outputEOL, currentEOL); + if (strlen(prevEOL) == 0) + strcpy(prevEOL, outputEOL); + if (strcmp(prevEOL, outputEOL) != 0) { - if (inStr[pos+ 1] == '\n') - { - // CRLF - if (lineEnd == LINEEND_CR) - { - outStr += inStr[pos]; // Delete the LF - pos++; - continue; - } - else if (lineEnd == LINEEND_LF) - { - outStr += inStr[pos+1]; // Delete the CR - pos++; - continue; - } - else - { - outStr += inStr[pos]; // Do not change - outStr += inStr[pos+1]; - pos++; - continue; - } - } - else - { - // CR - if (lineEnd == LINEEND_CRLF) - { - outStr += inStr[pos]; // Insert the CR - outStr += '\n'; // Insert the LF - continue; - } - else if (lineEnd == LINEEND_LF) - { - outStr += '\n'; // Insert the LF - continue; - } - else - { - outStr += inStr[pos]; // Do not change - continue; - } - } - } - else if (inStr[pos] == '\n') - { - // LF - if (lineEnd == LINEEND_CRLF) - { - outStr += '\r'; // Insert the CR - outStr += inStr[pos]; // Insert the LF - continue; - } - else if (lineEnd == LINEEND_CR) - { - outStr += '\r'; // Insert the CR - continue; - } - else - { - outStr += inStr[pos]; // Do not change - continue; - } - } - else - { - outStr += inStr[pos]; // Write the current char + lineEndsMixed = true; + filesAreIdentical = false; + strcpy(prevEOL, outputEOL); } } - // replace the stream - out.str(outStr); + else + { + strcpy(prevEOL, currentEOL); + if (strcmp(prevEOL, outputEOL) != 0) + filesAreIdentical = false; + } } -void ASConsole::correctMixedLineEnds(ostringstream& out) -{ - LineEndFormat lineEndFormat = LINEEND_DEFAULT; - if (strcmp(outputEOL, "\r\n") == 0) - lineEndFormat = LINEEND_WINDOWS; - if (strcmp(outputEOL, "\n") == 0) - lineEndFormat = LINEEND_LINUX; - if (strcmp(outputEOL, "\r") == 0) - lineEndFormat = LINEEND_MACOLD; - convertLineEnds(out, lineEndFormat); -} +#ifdef _WIN32 // Windows specific -void ASConsole::error(const char *why, const char* what) const +/** + * WINDOWS function to display the last system error. + */ +void ASConsole::displayLastError() { - (*_err) << why << ' ' << what << '\n' << endl; - (*_err) << "Artistic Style has terminated!" << endl; - exit(EXIT_FAILURE); + LPSTR msgBuf; + DWORD lastError = GetLastError(); + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + lastError, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPSTR) &msgBuf, + 0, + NULL + ); + // Display the string. + (*_err) << "Error (" << lastError << ") " << msgBuf << endl; + // Free the buffer. + LocalFree(msgBuf); } /** - * If no files have been given, use cin for input and cout for output. + * WINDOWS function to get the current directory. + * NOTE: getenv("CD") does not work for Windows Vista. + * The Windows function GetCurrentDirectory is used instead. * - * This is used to format text for text editors like TextWrangler (Mac). - * Do NOT display any console messages when this function is used. + * @return The path of the current directory */ -void ASConsole::formatCinToCout(ASFormatter& formatter) const +string ASConsole::getCurrentDirectory(const string& fileName_) const { - ASStreamIterator streamIterator(&cin); // create iterator for cin - formatter.init(&streamIterator); - - while (formatter.hasMoreLines()) - { - cout << formatter.nextLine(); - if (formatter.hasMoreLines()) - cout << streamIterator.getOutputEOL(); - } - cout.flush(); + char currdir[MAX_PATH]; + currdir[0] = '\0'; + if (!GetCurrentDirectory(sizeof(currdir), currdir)) + error("Cannot find file", fileName_.c_str()); + return string(currdir); } /** - * Open input file, format it, and close the output. + * WINDOWS function to resolve wildcards and recurse into sub directories. + * The fileName vector is filled with the path and names of files to process. * - * @param fileName The path and name of the file to be processed. - * @param formatter The formatter object. + * @param directory The path of the directory to be processed. + * @param wildcard The wildcard to be processed (e.g. *.cpp). */ -void ASConsole::formatFile(const string &fileName, ASFormatter &formatter) +void ASConsole::getFileNames(const string& directory, const string& wildcard) { - bool isFormatted = false; - - // open input file - ifstream in(fileName.c_str(), ios::binary); - if (!in) - error("Could not open input file", fileName.c_str()); + vector subDirectory; // sub directories of directory + WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile - ostringstream out; + // Find the first file in the directory + // Find will get at least "." and "..". + string firstFile = directory + "\\*"; + HANDLE hFind = FindFirstFile(firstFile.c_str(), &findFileData); - // Unless a specific language mode has been set, set the language mode - // according to the file's suffix. - if (!formatter.getModeManuallySet()) + if (hFind == INVALID_HANDLE_VALUE) { - if (stringEndsWith(fileName, string(".java"))) - formatter.setJavaStyle(); - else if (stringEndsWith(fileName, string(".cs"))) - formatter.setSharpStyle(); - else - formatter.setCStyle(); + // Error (3) The system cannot find the path specified. + // Error (123) The filename, directory name, or volume label syntax is incorrect. + // ::FindClose(hFind); before exiting + displayLastError(); + error("Cannot open directory", directory.c_str()); } - ASStreamIterator streamIterator(&in); - formatter.init(&streamIterator); - - // make sure encoding is 8 bit - // if not set the eofbit so the file is not formatted - FileEncoding encoding = getFileEncoding(in); - if (encoding != ENCODING_OK) - in.setstate(ios::eofbit); - - // set line end format - string nextLine; // next output line - filesAreIdentical = true; // input and output files are identical - LineEndFormat lineEndFormat = formatter.getLineEndFormat(); - initializeOutputEOL(lineEndFormat); - - // format the file - while (formatter.hasMoreLines()) + // save files and sub directories + do { - nextLine = formatter.nextLine(); - out << nextLine; - linesOut++; - if (formatter.hasMoreLines()) + // skip hidden or read only + if (findFileData.cFileName[0] == '.' + || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) + || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) + continue; + + // if a sub directory and recursive, save sub directory + if ((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && isRecursive) { - setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); - out << outputEOL; + string subDirectoryPath = directory + g_fileSeparator + findFileData.cFileName; + if (isPathExclued(subDirectoryPath)) + printMsg("exclude " + subDirectoryPath.substr(mainDirectoryLength)); + else + subDirectory.push_back(subDirectoryPath); + continue; } - else - streamIterator.saveLastInputLine(); // to compare the last input line - if (filesAreIdentical) + // save the file name + string filePathName = directory + g_fileSeparator + findFileData.cFileName; + // check exclude before wildcmp to avoid "unmatched exclude" error + bool isExcluded = isPathExclued(filePathName); + // save file name if wildcard match + if (wildcmp(wildcard.c_str(), findFileData.cFileName)) { - if (streamIterator.checkForEmptyLine) - { - if (nextLine.find_first_not_of(" \t") != string::npos) - filesAreIdentical = false; - } - else if (!streamIterator.compareToInputBuffer(nextLine)) - filesAreIdentical = false; - streamIterator.checkForEmptyLine = false; + if (isExcluded) + printMsg("exclude " + filePathName.substr(mainDirectoryLength)); + else + fileName.push_back(filePathName); } } - // correct for mixed line ends - if (lineEndsMixed) - { - correctMixedLineEnds(out); - filesAreIdentical = false; - } - in.close(); - - // if file has changed, write the new file - if (!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) - { - writeOutputFile(fileName, out); - isFormatted = true; - filesFormatted++; - } - else - filesUnchanged++; + while (FindNextFile(hFind, &findFileData) != 0); - if (encoding != ENCODING_OK) - printBadEncoding(encoding); + // check for processing error + ::FindClose(hFind); + DWORD dwError = GetLastError(); + if (dwError != ERROR_NO_MORE_FILES) + error("Error processing directory", directory.c_str()); - // remove targetDirectory from filename if required by print - string displayName; - if (hasWildcard) - displayName = fileName.substr(targetDirectory.length() + 1); - else - displayName = fileName; + // recurse into sub directories + // if not doing recursive subDirectory is empty + for (unsigned i = 0; i < subDirectory.size(); i++) + getFileNames(subDirectory[i], wildcard); - if (isFormatted) - printMsg("formatted " + displayName); - else - { - if (!isFormattedOnly || encoding != ENCODING_OK) - printMsg("unchanged* " + displayName); - } + return; } -// for unit testing -vector ASConsole::getExcludeHitsVector() +/** + * WINDOWS function to format a number according to the current locale. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * @param lcid The LCID of the locale to be used for testing. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, size_t lcid) const { - return excludeHitsVector; + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + assert(locale().name() == "C"); + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + + // format the number using the Windows API + if (lcid == 0) + lcid = LOCALE_USER_DEFAULT; + int outSize = ::GetNumberFormat(lcid, 0, number.c_str(), NULL, NULL, 0); + char* outBuf = new(nothrow) char[outSize]; + if (outBuf == NULL) + return number; + ::GetNumberFormat(lcid, 0, number.c_str(), NULL, outBuf, outSize); + + // remove the decimal + string formattedNum(outBuf); + int decSize = ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, NULL, 0); + char* decBuf = new(nothrow) char[decSize]; + if (decBuf == NULL) + return number; + ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, decBuf, decSize); + size_t i = formattedNum.rfind(decBuf); + if (i != string::npos) + formattedNum.erase(i); + + delete [] outBuf; + delete [] decBuf; + return formattedNum; } -// for unit testing -vector ASConsole::getExcludeVector() -{ return excludeVector; } +#else // not _WIN32 -// for unit testing -vector ASConsole::getFileName() -{ return fileName; } +/** + * LINUX function to get the current directory. + * This is done if the fileName does not contain a path. + * It is probably from an editor sending a single file. + * + * @param fileName_ The filename is used only for the error message. + * @return The path of the current directory + */ +string ASConsole::getCurrentDirectory(const string& fileName_) const +{ + char* currdir = getenv("PWD"); + if (currdir == NULL) + error("Cannot find file", fileName_.c_str()); + return string(currdir); +} -// for unit testing -vector ASConsole::getFileNameVector() -{ return fileNameVector; } +/** + * LINUX function to resolve wildcards and recurse into sub directories. + * The fileName vector is filled with the path and names of files to process. + * + * @param directory The path of the directory to be processed. + * @param wildcard The wildcard to be processed (e.g. *.cpp). + */ +void ASConsole::getFileNames(const string& directory, const string& wildcard) +{ + struct dirent* entry; // entry from readdir() + struct stat statbuf; // entry from stat() + vector subDirectory; // sub directories of this directory -// for unit testing -vector ASConsole::getFileOptionsVector() -{ return fileOptionsVector; } + // errno is defined in and is set for errors in opendir, readdir, or stat + errno = 0; -int ASConsole::getFilesUnchanged() -{ return filesUnchanged; } - -int ASConsole::getFilesFormatted() -{ return filesFormatted; } - -bool ASConsole::getIsFormattedOnly() -{ return isFormattedOnly; } - -bool ASConsole::getIsQuiet() -{ return isQuiet; } - -bool ASConsole::getIsRecursive() -{ return isRecursive; } - -bool ASConsole::getIsVerbose() -{ return isVerbose; } - -bool ASConsole::getLineEndsMixed() -{ return lineEndsMixed; } - -bool ASConsole::getNoBackup() -{ return noBackup; } - -string ASConsole::getOptionsFileName() -{ return optionsFileName; } - -bool ASConsole::getOptionsFileRequired() -{ return optionsFileRequired; } - -// for unit testing -vector ASConsole::getOptionsVector() -{ return optionsVector; } - -string ASConsole::getOrigSuffix() -{ return origSuffix; } - -bool ASConsole::getPreserveDate() -{ return preserveDate; } - -// initialize output end of line -void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat) -{ - assert(lineEndFormat == LINEEND_DEFAULT - || lineEndFormat == LINEEND_WINDOWS - || lineEndFormat == LINEEND_LINUX - || lineEndFormat == LINEEND_MACOLD); - - outputEOL[0] = '\0'; // current line end - prevEOL[0] = '\0'; // previous line end - lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only - - if (lineEndFormat == LINEEND_WINDOWS) - strcpy(outputEOL, "\r\n"); - else if (lineEndFormat == LINEEND_LINUX) - strcpy(outputEOL, "\n"); - else if (lineEndFormat == LINEEND_MACOLD) - strcpy(outputEOL, "\r"); - else - outputEOL[0] = '\0'; -} - -void ASConsole::printBadEncoding(FileEncoding encoding) const -{ - string msg = "********** following file unchanged: "; - if (encoding == UTF_16BE) - msg += "UTF-16BE encoding"; - else if (encoding == UTF_16LE) - msg += "UTF-16LE encoding"; - else if (encoding == UTF_32BE) - msg += "UTF-32BE encoding"; - else if (encoding == UTF_32LE) - msg += "UTF-32LE encoding"; - else - msg += "???????? encoding"; - printMsg(msg); -} - -void ASConsole::setIsFormattedOnly(bool state) -{ isFormattedOnly = state; } - -void ASConsole::setIsQuiet(bool state) -{ isQuiet = state; } - -void ASConsole::setIsRecursive(bool state) -{ isRecursive = state; } - -void ASConsole::setIsVerbose(bool state) -{ isVerbose = state; } - -void ASConsole::setNoBackup(bool state) -{ noBackup = state; } - -void ASConsole::setOptionsFileName(string name) -{ optionsFileName = name; } - -void ASConsole::setOptionsFileRequired(bool state) -{ optionsFileRequired = state; } - -void ASConsole::setOrigSuffix(string suffix) -{ origSuffix = suffix; } - -void ASConsole::setPreserveDate(bool state) -{ preserveDate = state; } - -// set outputEOL variable -void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL) -{ - if (lineEndFormat == LINEEND_DEFAULT) - { - strcpy(outputEOL, currentEOL); - if (strlen(prevEOL) == 0) - strcpy(prevEOL, outputEOL); - if (strcmp(prevEOL, outputEOL) != 0) - { - lineEndsMixed = true; - filesAreIdentical = false; - strcpy(prevEOL, outputEOL); - } - } - else - { - strcpy(prevEOL, currentEOL); - if (strcmp(prevEOL, outputEOL) != 0) - filesAreIdentical = false; - } -} - -#ifdef _WIN32 // Windows specific - -/** - * WINDOWS function to get the current directory. - * NOTE: getenv("CD") does not work for Windows Vista. - * The Windows function GetCurrentDirectory is used instead. - * - * @return The path of the current directory - */ -string ASConsole::getCurrentDirectory(const string &fileName) const -{ - char currdir[MAX_PATH]; - currdir[0] = '\0'; - if (!GetCurrentDirectory(sizeof(currdir), currdir)) - error("Cannot find file", fileName.c_str()); - return string(currdir); -} - -/** - * WINDOWS function to resolve wildcards and recurse into sub directories. - * The fileName vector is filled with the path and names of files to process. - * - * @param directory The path of the directory to be processed. - * @param wildcard The wildcard to be processed (e.g. *.cpp). - * @param fileName An empty vector which will be filled with the path and names of files to process. - */ -void ASConsole::getFileNames(const string &directory, const string &wildcard) -{ - vector subDirectory; // sub directories of directory - WIN32_FIND_DATA FindFileData; // for FindFirstFile and FindNextFile - - // Find the first file in the directory - string firstFile = directory + "\\*"; - HANDLE hFind = FindFirstFile(firstFile.c_str(), &FindFileData); - - if (hFind == INVALID_HANDLE_VALUE) - error("Cannot open directory", directory.c_str()); - - // save files and sub directories - do - { - // skip hidden or read only - if (FindFileData.cFileName[0] == '.' - || (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) - || (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) - continue; - - // if a sub directory and recursive, save sub directory - if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && isRecursive) - { - string subDirectoryPath = directory + g_fileSeparator + FindFileData.cFileName; - if (isPathExclued(subDirectoryPath)) - printMsg("exclude " + subDirectoryPath.substr(mainDirectoryLength)); - else - subDirectory.push_back(subDirectoryPath); - continue; - } - - // save the file name - string filePathName = directory + g_fileSeparator + FindFileData.cFileName; - // check exclude before wildcmp to avoid "unmatched exclude" error - bool isExcluded = isPathExclued(filePathName); - // save file name if wildcard match - if (wildcmp(wildcard.c_str(), FindFileData.cFileName)) - { - if (isExcluded) - printMsg("exclude " + filePathName.substr(mainDirectoryLength)); - else - fileName.push_back(filePathName); - } - } - while (FindNextFile(hFind, &FindFileData) != 0); - - // check for processing error - FindClose(hFind); - DWORD dwError = GetLastError(); - if (dwError != ERROR_NO_MORE_FILES) - error("Error processing directory", directory.c_str()); - - // recurse into sub directories - // if not doing recursive subDirectory is empty - for (unsigned i = 0; i < subDirectory.size(); i++) - { - getFileNames(subDirectory[i], wildcard); - } - - return; -} - -#else // not _WIN32 - -/** - * LINUX function to get the current directory. - * This is done if the fileName does not contain a path. - * It is probably from an editor sending a single file. - * - * @param fileName The filename is used only for the error message. - * @return The path of the current directory - */ -string ASConsole::getCurrentDirectory(const string &fileName) const -{ - char *currdir = getenv("PWD"); - if (currdir == NULL) - error("Cannot find file", fileName.c_str()); - return string(currdir); -} - -/** - * LINUX function to resolve wildcards and recurse into sub directories. - * The fileName vector is filled with the path and names of files to process. - * - * @param directory The path of the directory to be processed. - * @param wildcard The wildcard to be processed (e.g. *.cpp). - * @param fileName An empty vector which will be filled with the path and names of files to process. - */ -void ASConsole::getFileNames(const string &directory, const string &wildcard) -{ - struct dirent *entry; // entry from readdir() - struct stat statbuf; // entry from stat() - vector subDirectory; // sub directories of this directory - - // errno is defined in and is set for errors in opendir, readdir, or stat - errno = 0; - - DIR *dp = opendir(directory.c_str()); - if (dp == NULL) - error("Cannot open directory", directory.c_str()); + DIR* dp = opendir(directory.c_str()); + if (dp == NULL) + error("Cannot open directory", directory.c_str()); // save the first fileName entry for this recursion const unsigned firstEntry = fileName.size(); @@ -1446,6 +987,76 @@ return; } +/** + * LINUX function to get locale information and call getNumberFormat. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * @param For compatability with the Windows function. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, size_t) const +{ + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + assert(locale().name() == "C"); + + // get the locale info + struct lconv* lc; + lc = localeconv(); + + // format the number + return getNumberFormat(num, lc->grouping, lc->thousands_sep); +} + +/** + * LINUX function to format a number according to the current locale. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * @param groupingArg The grouping string from the locale. + * @param separator The thousands group separator from the locale. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, const char* groupingArg, const char* separator) const +{ + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + // format the number from right to left + string formattedNum; + size_t ig = 0; // grouping index + int grouping = groupingArg[ig]; + int i = number.length(); + // check for no grouping + if (grouping == 0) + grouping = number.length(); + while (i > 0) + { + // extract a group of numbers + string group; + if (i < grouping) + group = number.substr(0); + else + group = number.substr(i - grouping); + // update formatted number + formattedNum.insert(0, group); + i -= grouping; + if (i < 0) + i = 0; + if (i > 0) + formattedNum.insert(0, separator); + number.erase(i); + // update grouping + if (groupingArg[ig] != '\0' + && groupingArg[ig+1] != '\0') + grouping = groupingArg[++ig]; + } + return formattedNum; +} + #endif // _WIN32 // check files for 16 or 32 bit encoding @@ -1473,7 +1084,7 @@ } // get individual file names from the command-line file path -void ASConsole::getFilePaths(string &filePath) +void ASConsole::getFilePaths(string& filePath) { fileName.clear(); targetDirectory = string(); @@ -1507,10 +1118,21 @@ for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) excludeHitsVector[ix] = false; + // If the filename is not quoted on Linux, bash will replace the + // wildcard instead of passing it to the program. + if (isRecursive && !hasWildcard) + { + (*_err) << "Recursive option with no wildcard." << endl; +#ifndef _WIN32 + (*_err) << "Did you intend quote the filename?" << endl; +#endif + error(); + } + // display directory name for wildcard processing if (hasWildcard) { - printMsg("--------------------------------------------------"); + printSeparatingLine(); printMsg("directory " + targetDirectory + g_fileSeparator + targetFilename); } @@ -1521,7 +1143,7 @@ fileName.push_back(targetDirectory + g_fileSeparator + targetFilename); if (hasWildcard) - printMsg("--------------------------------------------------"); + printSeparatingLine(); // check for unprocessed excludes bool excludeErr = false; @@ -1533,14 +1155,22 @@ excludeErr = true; } } -#ifndef ASTYLECON_LIB - // abort if not a test + if (excludeErr) - exit(EXIT_FAILURE); -#endif + { + if (hasWildcard && !isRecursive) + (*_err) << "Did you intend to use --recursive?"<< endl; + error(); + } + // check if files were found (probably an input error if not) if (fileName.size() == 0) + { (*_err) << "No file to process " << filePath.c_str() << endl; + if (hasWildcard && !isRecursive) + (*_err) << "Did you intend to use --recursive?"<< endl; + error(); + } } bool ASConsole::fileNameVectorIsEmpty() @@ -1548,11 +1178,31 @@ return fileNameVector.empty(); } -// compare a path to the exclude vector -// used for both directories and filenames +bool ASConsole::isOption(const string& arg, const char* op) +{ + return arg.compare(op) == 0; +} + +bool ASConsole::isOption(const string& arg, const char* a, const char* b) +{ + return (isOption(arg, a) || isOption(arg, b)); +} + +bool ASConsole::isParamOption(const string& arg, const char* option) +{ + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if (retVal && strlen(option) == 1 && arg.length() > 1) + if (!isdigit(arg[1])) + retVal = false; + return retVal; +} + +// compare a path to the exclude vector +// used for both directories and filenames // updates the g_excludeHitsVector // return true if a match -bool ASConsole::isPathExclued(const string &subPath) +bool ASConsole::isPathExclued(const string& subPath) { bool retVal = false; @@ -1596,7 +1246,7 @@ void ASConsole::printHelp() const { (*_err) << endl; - (*_err) << " Artistic Style " << _version << endl; + (*_err) << " Artistic Style " << g_version << endl; (*_err) << " Maintained by: Jim Pattee\n"; (*_err) << " Original Author: Tal Davidson\n"; (*_err) << endl; @@ -1894,451 +1544,1000 @@ (*_err) << endl; } - -/** - * Process files in the fileNameVector. - * - * @param formatter The formatter object. - */ -void ASConsole::processFiles(ASFormatter &formatter) + +/** + * Process files in the fileNameVector. + */ +void ASConsole::processFiles() +{ + if (isVerbose) + printVerboseHeader(); + + clock_t startTime = clock(); // start time of file formatting + + // loop thru input fileNameVector and process the files + for (size_t i = 0; i < fileNameVector.size(); i++) + { + getFilePaths(fileNameVector[i]); + + // loop thru fileName vector formatting the files + for (size_t j = 0; j < fileName.size(); j++) + formatFile(fileName[j]); + } + + // files are processed, display stats + if (isVerbose) + printVerboseStats(startTime); +} + +// process options from the command line and options file +// build the vectors fileNameVector, excludeVector, optionsVector, and fileOptionsVector +void ASConsole::processOptions(vector& argvOptions) +{ + string arg; + bool ok = true; + bool shouldParseOptionsFile = true; + + // get command line options + for (size_t i = 0; i < argvOptions.size(); i++) + { + arg = argvOptions[i]; + + if ( isOption(arg, "--options=none") ) + { + shouldParseOptionsFile = false; + } + else if ( isParamOption(arg, "--options=") ) + { + optionsFileName = getParam(arg, "--options="); + optionsFileRequired = true; + if (optionsFileName.compare("") == 0) + setOptionsFileName(" "); + } + else if ( isOption(arg, "-h") + || isOption(arg, "--help") + || isOption(arg, "-?") ) + { + printHelp(); + exit(EXIT_SUCCESS); + } + else if ( isOption(arg, "-V" ) + || isOption(arg, "--version") ) + { + (*_err) << "Artistic Style Version " << g_version << endl; + exit(EXIT_SUCCESS); + } + else if (arg[0] == '-') + { + optionsVector.push_back(arg); + } + else // file-name + { + standardizePath(arg); + fileNameVector.push_back(arg); + } + } + + // get options file path and name + if (shouldParseOptionsFile) + { + if (optionsFileName.compare("") == 0) + { + char* env = getenv("ARTISTIC_STYLE_OPTIONS"); + if (env != NULL) + setOptionsFileName(env); + } + if (optionsFileName.compare("") == 0) + { + char* env = getenv("HOME"); + if (env != NULL) + setOptionsFileName(string(env) + "/.astylerc"); + } + if (optionsFileName.compare("") == 0) + { + char* env = getenv("USERPROFILE"); + if (env != NULL) + setOptionsFileName(string(env) + "/astylerc"); + } + if (optionsFileName.compare("") != 0) + standardizePath(optionsFileName); + } + + // create the options file vector and parse the options for errors + ASOptions options(formatter); + if (optionsFileName.compare("") != 0) + { + ifstream optionsIn(optionsFileName.c_str()); + if (optionsIn) + { + options.importOptions(optionsIn, fileOptionsVector); + ok = options.parseOptions(fileOptionsVector, + string("Invalid option file options: ")); + } + else + { + if (optionsFileRequired) + { + (*_err) << "Cannot open options file: " << optionsFileName.c_str() << endl; + error(); + } + optionsFileName.clear(); + } + optionsIn.close(); + } + if (!ok) + { + (*_err) << options.getOptionErrors() << endl; + (*_err) << "For help on options, type 'astyle -h' " << endl; + error(); + } + + // parse the command line options vector for errors + ok = options.parseOptions(optionsVector, + string("Invalid command line options: ")); + if (!ok) + { + (*_err) << options.getOptionErrors() << endl; + (*_err) << "For help on options, type 'astyle -h' \n" << endl; + error(); + } +} + +// remove a file and check for an error +void ASConsole::removeFile(const char* fileName_, const char* errMsg) const +{ + remove(fileName_); + if (errno == ENOENT) // no file is OK + errno = 0; + if (errno) + { + perror("errno message"); + error(errMsg, fileName_); + } +} + +// rename a file and check for an error +void ASConsole::renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const +{ + rename(oldFileName, newFileName); + // if file still exists the remove needs more time - retry + if (errno == EEXIST) + { + errno = 0; + waitForRemove(newFileName); + rename(oldFileName, newFileName); + } + if (errno) + { + perror("errno message"); + error(errMsg, oldFileName); + } +} + +// make sure file separators are correct type (Windows or Linux) +// remove ending file separator +// remove beginning file separator if requested and NOT a complete file path +void ASConsole::standardizePath(string& path, bool removeBeginningSeparator /*false*/) const +{ +#ifdef __VMS + struct FAB fab; + struct NAML naml; + char less[NAML$C_MAXRSS]; + char sess[NAM$C_MAXRSS]; + int r0_status; + + // If we are on a VMS system, translate VMS style filenames to unix + // style. + fab = cc$rms_fab; + fab.fab$l_fna = (char*)-1; + fab.fab$b_fns = 0; + fab.fab$l_naml = &naml; + naml = cc$rms_naml; + strcpy (sess, path.c_str()); + naml.naml$l_long_filename = (char*)sess; + naml.naml$l_long_filename_size = path.length(); + naml.naml$l_long_expand = less; + naml.naml$l_long_expand_alloc = sizeof (less); + naml.naml$l_esa = sess; + naml.naml$b_ess = sizeof (sess); + naml.naml$v_no_short_upcase = 1; + r0_status = sys$parse (&fab); + if (r0_status == RMS$_SYN) + { + error("File syntax error", path.c_str()); + } + else + { + if (!$VMS_STATUS_SUCCESS(r0_status)) + { + (void)lib$signal (r0_status); + } + } + less[naml.naml$l_long_expand_size - naml.naml$b_ver] = '\0'; + sess[naml.naml$b_esl - naml.naml$b_ver] = '\0'; + if (naml.naml$l_long_expand_size > naml.naml$b_esl) + { + path = decc$translate_vms (less); + } + else + { + path = decc$translate_vms (sess); + } +#endif /* __VMS */ + + // make sure separators are correct type (Windows or Linux) + for (size_t i = 0; i < path.length(); i++) + { + i = path.find_first_of("/\\", i); + if (i == string::npos) + break; + path[i] = g_fileSeparator; + } + // remove separator from the end + if (path[path.length()-1] == g_fileSeparator) + path.erase(path.length()-1, 1); + // remove beginning separator if requested + if (removeBeginningSeparator && (path[0] == g_fileSeparator)) + path.erase(0, 1); +} + +void ASConsole::printMsg(const string& msg) const +{ + if (isQuiet) + return; + printf("%s\n", msg.c_str()); +} + +void ASConsole::printSeparatingLine() const +{ + string line; + for (size_t i = 0; i < 60; i++) + line.append("-"); + printMsg(line); +} + +void ASConsole::printVerboseHeader() const +{ + assert(isVerbose); + if (isQuiet) + return; + printf("Artistic Style %s\n", g_version); + if (!optionsFileName.empty()) + printf("Using default options file %s\n", optionsFileName.c_str()); +} + +void ASConsole::printVerboseStats(clock_t startTime) const +{ + assert(isVerbose); + if (isQuiet) + return; + if (hasWildcard) + printSeparatingLine(); + string formatted = getNumberFormat(filesFormatted); + string unchanged = getNumberFormat(filesUnchanged); + printf(" %s formatted; %s unchanged; ", formatted.c_str(), unchanged.c_str()); + + // show processing time + clock_t stopTime = clock(); + float secs = (stopTime - startTime) / float (CLOCKS_PER_SEC); + if (secs < 60) + { + if (secs < 2) + printf("%.2f", secs); + else if (secs < 20) + printf("%.1f", secs); + else + printf("%.0f", secs); + printf("%s", " seconds; "); + } + else + { + // show minutes and seconds if time is greater than one minute + int min = (int) secs / 60; + secs -= min * 60; + int minsec = int (secs + .5); + printf("%d min %d sec; ", min, minsec); + } + + string lines = getNumberFormat(linesOut); + printf("%s lines\n", lines.c_str()); +} + +bool ASConsole::stringEndsWith(const string& str, const string& suffix) const +{ + int strIndex = (int) str.length() - 1; + int suffixIndex = (int) suffix.length() - 1; + + while (strIndex >= 0 && suffixIndex >= 0) + { + if (tolower(str[strIndex]) != tolower(suffix[suffixIndex])) + return false; + + --strIndex; + --suffixIndex; + } + // suffix longer than string + if (strIndex < 0 && suffixIndex >= 0) + return false; + return true; +} + +void ASConsole::updateExcludeVector(string suffixParam) { - if (isVerbose) - printVerboseHeader(); + excludeVector.push_back(suffixParam); + standardizePath(excludeVector.back(), true); + excludeHitsVector.push_back(false); +} - clock_t startTime = clock(); // start time of file formatting +void ASConsole::sleep(int seconds) const +{ + clock_t endwait; + endwait = clock_t (clock () + seconds * CLOCKS_PER_SEC); + while (clock() < endwait) {} +} - // loop thru input fileNameVector and process the files - for (size_t i = 0; i < fileNameVector.size(); i++) +int ASConsole::waitForRemove(const char* newFileName) const +{ + struct stat stBuf; + int seconds; + // sleep a max of 20 seconds for the remove + for (seconds = 1; seconds <= 20; seconds++) { - getFilePaths(fileNameVector[i]); - - // loop thru fileName vector formatting the files - for (size_t j = 0; j < fileName.size(); j++) - formatFile(fileName[j], formatter); + sleep(1); + if (stat(newFileName, &stBuf) != 0) + break; } - - // files are processed, display stats - if (isVerbose) - printVerboseStats(startTime); - + errno = 0; + return seconds; } -// process options from the command line and options file -// build the vectors fileNameVector, excludeVector, optionsVector, and fileOptionsVector -processReturn ASConsole::processOptions(int argc, char** argv, ASFormatter &formatter) +// From The Code Project http://www.codeproject.com/string/wildcmp.asp +// Written by Jack Handy - jakkhandy@hotmail.com +// Modified to compare case insensitive for Windows +int ASConsole::wildcmp(const char* wild, const char* data) const { - string arg; - bool ok = true; - bool shouldParseOptionsFile = true; + const char* cp = NULL, *mp = NULL; + bool cmpval; - // get command line options - for (int i = 1; i < argc; i++) + while ((*data) && (*wild != '*')) { - arg = string(argv[i]); + if (!g_isCaseSensitive) + cmpval = (tolower(*wild) != tolower(*data)) && (*wild != '?'); + else + cmpval = (*wild != *data) && (*wild != '?'); - if ( IS_OPTION(arg, "--options=none") ) - { - shouldParseOptionsFile = false; - } - else if ( isParamOption(arg, "--options=") ) + if (cmpval) { - optionsFileName = GET_PARAM(arg, "--options="); - optionsFileRequired = true; - if (optionsFileName.compare("") == 0) - setOptionsFileName(" "); + return 0; } - else if ( IS_OPTION(arg, "-h") - || IS_OPTION(arg, "--help") - || IS_OPTION(arg, "-?") ) + wild++; + data++; + } + + while (*data) + { + if (*wild == '*') { - printHelp(); - return(END_SUCCESS); + if (!*++wild) + { + return 1; + } + mp = wild; + cp = data+1; } - else if ( IS_OPTION(arg, "-V" ) - || IS_OPTION(arg, "--version") ) + else { - (*_err) << "Artistic Style Version " << _version << endl; - return(END_SUCCESS); + if (!g_isCaseSensitive) + cmpval = (tolower(*wild) == tolower(*data) || (*wild == '?')); + else + cmpval = (*wild == *data) || (*wild == '?'); + + if (cmpval) + { + wild++; + data++; + } + else + { + wild = mp; + data = cp++; + } } - else if (arg[0] == '-') + } + + while (*wild == '*') + { + wild++; + } + return !*wild; +} + +void ASConsole::writeOutputFile(const string& fileName_, ostringstream& out) const +{ + // save date accessed and date modified of original file + struct stat stBuf; + bool statErr = false; + if (stat(fileName_.c_str(), &stBuf) == -1) + statErr = true; + + // create a backup + if (!noBackup) + { + string origFileName = fileName_ + origSuffix; + removeFile(origFileName.c_str(), "Cannot remove pre-existing backup file"); + renameFile(fileName_.c_str(), origFileName.c_str(), "Cannot create backup file"); + } + + // write the output file + ofstream fout(fileName_.c_str(), ios::binary | ios::trunc); + if (!fout) + error("Cannot open output file", fileName_.c_str()); + fout << out.str(); + fout.close(); + + // change date modified to original file date + // Embarcadero must be linked with cw32mt not cw32 + if (preserveDate) + { + if (!statErr) { - optionsVector.push_back(arg); + struct utimbuf outBuf; + outBuf.actime = stBuf.st_atime; + // add ticks so 'make' will recoginze a change + // Visual Studio 2008 needs more than 1 + outBuf.modtime = stBuf.st_mtime + 10; + if (utime(fileName_.c_str(), &outBuf) == -1) + statErr = true; } - else // file-name + if (statErr) { - standardizePath(arg); - fileNameVector.push_back(arg); + perror("errno message"); + (*_err) << "********* Cannot preserve file date" << endl; } } +} - // get options file path and name - if (shouldParseOptionsFile) +#endif // ASConsole: + +//----------------------------------------------------------------------------- +// ASOptions class +// used by both console and library builds +//----------------------------------------------------------------------------- + +/** + * parse the options vector + * optionsVector can be either a fileOptionsVector (options file) or an optionsVector (command line) + * + * @return true if no errors, false if errors + */ +bool ASOptions::parseOptions(vector &optionsVector, const string& errorInfo) +{ + vector::iterator option; + string arg, subArg; + optionErrors.clear(); + + for (option = optionsVector.begin(); option != optionsVector.end(); ++option) { - if (optionsFileName.compare("") == 0) + arg = *option; + + if (arg.compare(0, 2, "--") == 0) + parseOption(arg.substr(2), errorInfo); + else if (arg[0] == '-') { - char* env = getenv("ARTISTIC_STYLE_OPTIONS"); - if (env != NULL) - setOptionsFileName(env); + size_t i; + + for (i = 1; i < arg.length(); ++i) + { + if (isalpha(arg[i]) && i > 1) + { + parseOption(subArg, errorInfo); + subArg = ""; + } + subArg.append(1, arg[i]); + } + parseOption(subArg, errorInfo); + subArg = ""; } - if (optionsFileName.compare("") == 0) + else { - char* env = getenv("HOME"); - if (env != NULL) - setOptionsFileName(string(env) + "/.astylerc"); + parseOption(arg, errorInfo); + subArg = ""; } - if (optionsFileName.compare("") == 0) + } + if (optionErrors.str().length() > 0) + return false; + return true; +} + +void ASOptions::parseOption(const string& arg, const string& errorInfo) +{ + if ( isOption(arg, "style=allman") || isOption(arg, "style=ansi") || isOption(arg, "style=bsd") ) + { + formatter.setFormattingStyle(STYLE_ALLMAN); + } + else if ( isOption(arg, "style=java") ) + { + formatter.setFormattingStyle(STYLE_JAVA); + } + else if ( isOption(arg, "style=k&r") || isOption(arg, "style=kr") || isOption(arg, "style=k/r") ) + { + formatter.setFormattingStyle(STYLE_KR); + } + else if ( isOption(arg, "style=stroustrup") ) + { + formatter.setFormattingStyle(STYLE_STROUSTRUP); + } + else if ( isOption(arg, "style=whitesmith") ) + { + formatter.setFormattingStyle(STYLE_WHITESMITH); + } + else if ( isOption(arg, "style=banner") ) + { + formatter.setFormattingStyle(STYLE_BANNER); + } + else if ( isOption(arg, "style=gnu") ) + { + formatter.setFormattingStyle(STYLE_GNU); + } + else if ( isOption(arg, "style=linux") ) + { + formatter.setFormattingStyle(STYLE_LINUX); + } + else if ( isOption(arg, "style=horstmann") ) + { + formatter.setFormattingStyle(STYLE_HORSTMANN); + } + else if ( isOption(arg, "style=1tbs") || isOption(arg, "style=otbs") ) + { + formatter.setFormattingStyle(STYLE_1TBS); + } + else if ( isParamOption(arg, "A") ) + { + int style = 0; + string styleParam = getParam(arg, "A"); + if (styleParam.length() > 0) + style = atoi(styleParam.c_str()); + if (style < 1 || style > 10) + isOptionError(arg, errorInfo); + else if (style == 1) + formatter.setFormattingStyle(STYLE_ALLMAN); + else if (style == 2) + formatter.setFormattingStyle(STYLE_JAVA); + else if (style == 3) + formatter.setFormattingStyle(STYLE_KR); + else if (style == 4) + formatter.setFormattingStyle(STYLE_STROUSTRUP); + else if (style == 5) + formatter.setFormattingStyle(STYLE_WHITESMITH); + else if (style == 6) + formatter.setFormattingStyle(STYLE_BANNER); + else if (style == 7) + formatter.setFormattingStyle(STYLE_GNU); + else if (style == 8) + formatter.setFormattingStyle(STYLE_LINUX); + else if (style == 9) + formatter.setFormattingStyle(STYLE_HORSTMANN); + else if (style == 10) + formatter.setFormattingStyle(STYLE_1TBS); + } + // must check for mode=cs before mode=c !!! + else if ( isOption(arg, "mode=cs") ) + { + formatter.setSharpStyle(); + formatter.setModeManuallySet(true); + } + else if ( isOption(arg, "mode=c") ) + { + formatter.setCStyle(); + formatter.setModeManuallySet(true); + } + else if ( isOption(arg, "mode=java") ) + { + formatter.setJavaStyle(); + formatter.setModeManuallySet(true); + } + else if ( isParamOption(arg, "t", "indent=tab=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "t", "indent=tab="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else { - char* env = getenv("USERPROFILE"); - if (env != NULL) - setOptionsFileName(string(env) + "/astylerc"); + formatter.setTabIndentation(spaceNum, false); + formatter.setIndentManuallySet(true); } - if (optionsFileName.compare("") != 0) - standardizePath(optionsFileName); } - - // create the options file vector and parse the options for errors - if (optionsFileName.compare("") != 0) + else if ( isOption(arg, "indent=tab") ) { - ifstream optionsIn(optionsFileName.c_str()); - if (optionsIn) + formatter.setTabIndentation(4); + // do NOT call setIndentManuallySet(true); + } + else if ( isParamOption(arg, "T", "indent=force-tab=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "T", "indent=force-tab="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else { - importOptions(optionsIn, fileOptionsVector); - ok = parseOptions(formatter, - fileOptionsVector.begin(), - fileOptionsVector.end(), - string("Invalid option in default options file: ")); + formatter.setTabIndentation(spaceNum, true); + formatter.setIndentManuallySet(true); } + } + else if ( isOption(arg, "indent=force-tab") ) + { + formatter.setTabIndentation(4, true); + // do NOT call setIndentManuallySet(true); + } + else if ( isParamOption(arg, "s", "indent=spaces=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "s", "indent=spaces="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); else { - if (optionsFileRequired) - { - (*_err) << "Could not open options file: " << optionsFileName.c_str() << endl; - return (END_FAILURE); - } - optionsFileName.clear(); + formatter.setSpaceIndentation(spaceNum); + formatter.setIndentManuallySet(true); } - optionsIn.close(); } - if (!ok) + else if ( isOption(arg, "indent=spaces") ) { - (*_err) << "For help on options, type 'astyle -h' " << endl; - return(END_FAILURE); + formatter.setSpaceIndentation(4); + // do NOT call setIndentManuallySet(true); } - - // parse the command line options vector for errors - ok = parseOptions(formatter, - optionsVector.begin(), - optionsVector.end(), - string("Invalid command line option: ")); - if (!ok) + else if ( isParamOption(arg, "m", "min-conditional-indent=") ) { - (*_err) << "For help on options, type 'astyle -h' \n" << endl; - return(END_FAILURE); + int minIndent = MINCOND_TWO; + string minIndentParam = getParam(arg, "m", "min-conditional-indent="); + if (minIndentParam.length() > 0) + minIndent = atoi(minIndentParam.c_str()); + if (minIndent >= MINCOND_END) + isOptionError(arg, errorInfo); + else + formatter.setMinConditionalIndentOption(minIndent); } - return(CONTINUE); -} - -// remove a file and check for an error -void ASConsole::removeFile(const char* fileName, const char* errMsg) const -{ - remove(fileName); - if (errno == ENOENT) // no file is OK - errno = 0; - if (errno) + else if ( isParamOption(arg, "M", "max-instatement-indent=") ) { - perror("errno message"); - error(errMsg, fileName); + int maxIndent = 40; + string maxIndentParam = getParam(arg, "M", "max-instatement-indent="); + if (maxIndentParam.length() > 0) + maxIndent = atoi(maxIndentParam.c_str()); + if (maxIndent > 80) + isOptionError(arg, errorInfo); + else + formatter.setMaxInStatementIndentLength(maxIndent); } -} - -// rename a file and check for an error -void ASConsole::renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const -{ - rename(oldFileName, newFileName); - // if file still exists the remove needs more time - retry - if (errno == EEXIST) + else if ( isOption(arg, "B", "indent-brackets") ) { - errno = 0; - waitForRemove(newFileName); - rename(oldFileName, newFileName); + formatter.setBracketIndent(true); } - if (errno) + else if ( isOption(arg, "G", "indent-blocks") ) { - perror("errno message"); - error(errMsg, oldFileName); + formatter.setBlockIndent(true); } -} - -// make sure file separators are correct type (Windows or Linux) -// remove ending file separator -// remove beginning file separator if requested and NOT a complete file path -void ASConsole::standardizePath(string &path, bool removeBeginningSeparator /*false*/) const -{ -#ifdef __VMS - struct FAB fab; - struct NAML naml; - char less[NAML$C_MAXRSS]; - char sess[NAM$C_MAXRSS]; - int r0_status; - - // If we are on a VMS system, translate VMS style filenames to unix - // style. - fab = cc$rms_fab; - fab.fab$l_fna = (char *)-1; - fab.fab$b_fns = 0; - fab.fab$l_naml = &naml; - naml = cc$rms_naml; - strcpy (sess, path.c_str()); - naml.naml$l_long_filename = (char *)sess; - naml.naml$l_long_filename_size = path.length(); - naml.naml$l_long_expand = less; - naml.naml$l_long_expand_alloc = sizeof (less); - naml.naml$l_esa = sess; - naml.naml$b_ess = sizeof (sess); - naml.naml$v_no_short_upcase = 1; - r0_status = sys$parse (&fab); - if (r0_status == RMS$_SYN) + else if ( isOption(arg, "N", "indent-namespaces") ) + { + formatter.setNamespaceIndent(true); + } + else if ( isOption(arg, "C", "indent-classes") ) + { + formatter.setClassIndent(true); + } + else if ( isOption(arg, "S", "indent-switches") ) + { + formatter.setSwitchIndent(true); + } + else if ( isOption(arg, "K", "indent-cases") ) + { + formatter.setCaseIndent(true); + } + else if ( isOption(arg, "L", "indent-labels") ) + { + formatter.setLabelIndent(true); + } + else if ( isOption(arg, "y", "break-closing-brackets") ) + { + formatter.setBreakClosingHeaderBracketsMode(true); + } + else if ( isOption(arg, "b", "brackets=break") ) + { + formatter.setBracketFormatMode(BREAK_MODE); + } + else if ( isOption(arg, "a", "brackets=attach") ) + { + formatter.setBracketFormatMode(ATTACH_MODE); + } + else if ( isOption(arg, "l", "brackets=linux") ) + { + formatter.setBracketFormatMode(LINUX_MODE); + } + else if ( isOption(arg, "u", "brackets=stroustrup") ) + { + formatter.setBracketFormatMode(STROUSTRUP_MODE); + } + else if ( isOption(arg, "g", "brackets=horstmann") ) + { + formatter.setBracketFormatMode(HORSTMANN_MODE); + } + else if ( isOption(arg, "O", "keep-one-line-blocks") ) + { + formatter.setBreakOneLineBlocksMode(false); + } + else if ( isOption(arg, "o", "keep-one-line-statements") ) + { + formatter.setSingleStatementsMode(false); + } + else if ( isOption(arg, "P", "pad-paren") ) + { + formatter.setParensOutsidePaddingMode(true); + formatter.setParensInsidePaddingMode(true); + } + else if ( isOption(arg, "d", "pad-paren-out") ) + { + formatter.setParensOutsidePaddingMode(true); + } + else if ( isOption(arg, "D", "pad-paren-in") ) + { + formatter.setParensInsidePaddingMode(true); + } + else if ( isOption(arg, "H", "pad-header") ) + { + formatter.setParensHeaderPaddingMode(true); + } + else if ( isOption(arg, "U", "unpad-paren") ) + { + formatter.setParensUnPaddingMode(true); + } + else if ( isOption(arg, "p", "pad-oper") ) + { + formatter.setOperatorPaddingMode(true); + } + else if ( isOption(arg, "x", "delete-empty-lines") ) + { + formatter.setDeleteEmptyLinesMode(true); + } + else if ( isOption(arg, "E", "fill-empty-lines") ) + { + formatter.setEmptyLineFill(true); + } + else if ( isOption(arg, "w", "indent-preprocessor") ) + { + formatter.setPreprocessorIndent(true); + } + else if ( isOption(arg, "c", "convert-tabs") ) + { + formatter.setTabSpaceConversionMode(true); + } + else if ( isOption(arg, "F", "break-blocks=all") ) + { + formatter.setBreakBlocksMode(true); + formatter.setBreakClosingHeaderBlocksMode(true); + } + else if ( isOption(arg, "f", "break-blocks") ) + { + formatter.setBreakBlocksMode(true); + } + else if ( isOption(arg, "e", "break-elseifs") ) + { + formatter.setBreakElseIfsMode(true); + } + else if ( isOption(arg, "j", "add-brackets") ) + { + formatter.setAddBracketsMode(true); + } + else if ( isOption(arg, "J", "add-one-line-brackets") ) + { + formatter.setAddOneLineBracketsMode(true); + } + else if ( isOption(arg, "Y", "indent-col1-comments") ) + { + formatter.setIndentCol1CommentsMode(true); + } + else if ( isOption(arg, "align-pointer=type") ) + { + formatter.setPointerAlignment(ALIGN_TYPE); + } + else if ( isOption(arg, "align-pointer=middle") ) + { + formatter.setPointerAlignment(ALIGN_MIDDLE); + } + else if ( isOption(arg, "align-pointer=name") ) + { + formatter.setPointerAlignment(ALIGN_NAME); + } + else if ( isParamOption(arg, "k") ) + { + int align = 0; + string styleParam = getParam(arg, "k"); + if (styleParam.length() > 0) + align = atoi(styleParam.c_str()); + if (align < 1 || align > 3) + isOptionError(arg, errorInfo); + else if (align == 1) + formatter.setPointerAlignment(ALIGN_TYPE); + else if (align == 2) + formatter.setPointerAlignment(ALIGN_MIDDLE); + else if (align == 3) + formatter.setPointerAlignment(ALIGN_NAME); + } + // depreciated options //////////////////////////////////////////////////////////////////////// + // depreciated in release 1.23 + // removed from documentation in release 1.24 + // removed from source in release 2.01 (1.25) + // end depreciated options //////////////////////////////////////////////////////////////////// +#ifdef ASTYLE_LIB + // End of options used by GUI ///////////////////////////////////////////////////////////////// + else + isOptionError(arg, errorInfo); +#else + // Options used by only console /////////////////////////////////////////////////////////////// + else if ( isOption(arg, "n", "suffix=none") ) + { + g_console->setNoBackup(true); + } + else if ( isParamOption(arg, "suffix=") ) + { + string suffixParam = getParam(arg, "suffix="); + if (suffixParam.length() > 0) + { + g_console->setOrigSuffix(suffixParam); + } + } + else if ( isParamOption(arg, "exclude=") ) + { + string suffixParam = getParam(arg, "exclude="); + if (suffixParam.length() > 0) + g_console->updateExcludeVector(suffixParam); + } + else if ( isOption(arg, "r", "R") || isOption(arg, "recursive") ) + { + g_console->setIsRecursive(true); + } + else if ( isOption(arg, "Z", "preserve-date") ) { - error("File syntax error", path.c_str()); + g_console->setPreserveDate(true); } - else + else if ( isOption(arg, "v", "verbose") ) { - if (!$VMS_STATUS_SUCCESS(r0_status)) - { - (void)lib$signal (r0_status); - } + g_console->setIsVerbose(true); } - less[naml.naml$l_long_expand_size - naml.naml$b_ver] = '\0'; - sess[naml.naml$b_esl - naml.naml$b_ver] = '\0'; - if (naml.naml$l_long_expand_size > naml.naml$b_esl) + else if ( isOption(arg, "Q", "formatted") ) { - path = decc$translate_vms (less); + g_console->setIsFormattedOnly(true); } - else + else if ( isOption(arg, "q", "quiet") ) { - path = decc$translate_vms (sess); + g_console->setIsQuiet(true); } -#endif /* __VMS */ - - // make sure separators are correct type (Windows or Linux) - for (size_t i = 0; i < path.length(); i++) + else if ( isOption(arg, "X", "errors-to-stdout") ) { - i = path.find_first_of("/\\", i); - if (i == string::npos) - break; - path[i] = g_fileSeparator; + _err = &cout; } - // remove separator from the end - if (path[path.length()-1] == g_fileSeparator) - path.erase(path.length()-1, 1); - // remove beginning separator if requested - if (removeBeginningSeparator && (path[0] == g_fileSeparator)) - path.erase(0, 1); -} - -void ASConsole::printMsg(const string &msg) const -{ - if (isQuiet) - return; - cout << msg << endl; -} - -void ASConsole::printVerboseHeader() const -{ - assert(isVerbose); - if (isQuiet) - return; - cout << "Artistic Style " << _version << endl; - if (optionsFileName.compare("") != 0) - cout << "Using default options file " << optionsFileName << endl; -} - -void ASConsole::printVerboseStats(clock_t startTime) const -{ - assert(isVerbose); - if (isQuiet) - return; - if (hasWildcard) - cout << "--------------------------------------------------" << endl; - cout << filesFormatted << " formatted, "; - cout << filesUnchanged << " unchanged, "; - - // show processing time - clock_t stopTime = clock(); - float secs = float ((stopTime - startTime) / CLOCKS_PER_SEC); - if (secs < 60) + else if ( isOption(arg, "lineend=windows") ) { - // show tenths of a second if time is less than 20 seconds - cout.precision(2); - if (secs >= 10 && secs < 20) - cout.precision(3); - cout << secs << " seconds, "; - cout.precision(0); + formatter.setLineEndFormat(LINEEND_WINDOWS); } - else + else if ( isOption(arg, "lineend=linux") ) { - // show minutes and seconds if time is greater than one minute - int min = (int) secs / 60; - secs -= min * 60; - int minsec = int (secs + .5); - cout << min << " min " << minsec << " sec, "; + formatter.setLineEndFormat(LINEEND_LINUX); } + else if ( isOption(arg, "lineend=macold") ) + { + formatter.setLineEndFormat(LINEEND_MACOLD); + } + else if ( isParamOption(arg, "z") ) + { + int lineendType = 0; + string lineendParam = getParam(arg, "z"); + if (lineendParam.length() > 0) + lineendType = atoi(lineendParam.c_str()); + if (lineendType < 1 || lineendType > 3) + isOptionError(arg, errorInfo); + else if (lineendType == 1) + formatter.setLineEndFormat(LINEEND_WINDOWS); + else if (lineendType == 2) + formatter.setLineEndFormat(LINEEND_LINUX); + else if (lineendType == 3) + formatter.setLineEndFormat(LINEEND_MACOLD); + } + else + isOptionError(arg, errorInfo); +#endif +} // End of parseOption function - cout << linesOut << " lines" << endl; -} - -bool ASConsole::stringEndsWith(const string &str, const string &suffix) const +void ASOptions::importOptions(istream& in, vector &optionsVector) { - int strIndex = (int) str.length() - 1; - int suffixIndex = (int) suffix.length() - 1; + char ch; + string currentToken; - while (strIndex >= 0 && suffixIndex >= 0) + while (in) { - if (tolower(str[strIndex]) != tolower(suffix[suffixIndex])) - return false; + currentToken = ""; + do + { + in.get(ch); + if (in.eof()) + break; + // treat '#' as line comments + if (ch == '#') + while (in) + { + in.get(ch); + if (ch == '\n') + break; + } - --strIndex; - --suffixIndex; + // break options on spaces, tabs, commas, or new-lines + if (in.eof() || ch == ' ' || ch == '\t' || ch == ',' || ch == '\n') + break; + else + currentToken.append(1, ch); + + } + while (in); + + if (currentToken.length() != 0) + optionsVector.push_back(currentToken); } - // suffix longer than string - if (strIndex < 0 && suffixIndex >= 0) - return false; - return true; } -void ASConsole::updateExcludeVector(string suffixParam) +string ASOptions::getOptionErrors() { - excludeVector.push_back(suffixParam); - standardizePath(excludeVector.back(), true); - excludeHitsVector.push_back(false); + return optionErrors.str(); } -void ASConsole::sleep(int seconds) const +string ASOptions::getParam(const string& arg, const char* op) { - clock_t endwait; - endwait = clock_t (clock () + seconds * CLOCKS_PER_SEC); - while (clock() < endwait) {} + return arg.substr(strlen(op)); } -int ASConsole::waitForRemove(const char* newFileName) const +string ASOptions::getParam(const string& arg, const char* op1, const char* op2) { - struct stat stBuf; - int seconds; - // sleep a max of 20 seconds for the remove - for (seconds = 0; seconds < 20; seconds++) - { - sleep(1); - if (stat(newFileName, &stBuf) != 0) - break; - } - errno = 0; - return seconds; + return isParamOption(arg, op1) ? getParam(arg, op1) : getParam(arg, op2); } -// From The Code Project http://www.codeproject.com/string/wildcmp.asp -// Written by Jack Handy - jakkhandy@hotmail.com -// Modified to compare case insensitive for Windows -int ASConsole::wildcmp(const char *wild, const char *data) const +bool ASOptions::isOption(const string arg, const char* op) { - const char *cp = NULL, *mp = NULL; - bool cmpval; - - while ((*data) && (*wild != '*')) - { - if (!g_isCaseSensitive) - cmpval = (tolower(*wild) != tolower(*data)) && (*wild != '?'); - else - cmpval = (*wild != *data) && (*wild != '?'); - - if (cmpval) - { - return 0; - } - wild++; - data++; - } - - while (*data) - { - if (*wild == '*') - { - if (!*++wild) - { - return 1; - } - mp = wild; - cp = data+1; - } - else - { - if (!g_isCaseSensitive) - cmpval = (tolower(*wild) == tolower(*data) || (*wild == '?')); - else - cmpval = (*wild == *data) || (*wild == '?'); - - if (cmpval) - { - wild++; - data++; - } - else - { - wild = mp; - data = cp++; - } - } - } - - while (*wild == '*') - { - wild++; - } - return !*wild; + return arg.compare(op) == 0; } -void ASConsole::writeOutputFile(const string &fileName, ostringstream &out) const +bool ASOptions::isOption(const string& arg, const char* op1, const char* op2) { - // save date accessed and date modified of original file - struct stat stBuf; - bool statErr = false; - if (stat(fileName.c_str(), &stBuf) == -1) - statErr = true; + return (isOption(arg, op1) || isOption(arg, op2)); +} - // create a backup - if (!noBackup) - { - string origFileName = fileName + origSuffix; - removeFile(origFileName.c_str(), "Could not remove pre-existing backup file"); - renameFile(fileName.c_str(), origFileName.c_str(), "Could not create backup file"); - } +void ASOptions::isOptionError(const string& arg, const string& errorInfo) +{ + if (optionErrors.str().length() == 0) + optionErrors << errorInfo << endl; // need main error message + optionErrors << arg << endl; +} - // write the output file - ofstream fout(fileName.c_str(), ios::binary | ios::trunc); - if (!fout) - error("Could not open output file", fileName.c_str()); - fout << out.str(); - fout.close(); +bool ASOptions::isParamOption(const string& arg, const char* option) +{ + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if (retVal && strlen(option) == 1 && arg.length() > 1) + if (!isdigit(arg[1])) + retVal = false; + return retVal; +} - // change date modified to original file date - if (preserveDate) - { - if (!statErr) - { - struct utimbuf outBuf; - outBuf.actime = stBuf.st_atime; - // add ticks so 'make' will recoginze a change - // Visual Studio 2008 needs more than 1 - outBuf.modtime = stBuf.st_mtime + 10; - if (utime(fileName.c_str(), &outBuf) == -1) - statErr = true; - } - if (statErr) - (*_err) << "********* could not preserve following file date" << endl; - } +bool ASOptions::isParamOption(const string& arg, const char* option1, const char* option2) +{ + return isParamOption(arg, option1) || isParamOption(arg, option2); } -#endif -// ******************* end of console functions *********************************************** + +// ******************* end of ASOptions functions ********************************************* } // end of namespace astyle @@ -2347,13 +2546,13 @@ using namespace astyle; #ifdef ASTYLE_JNI -// ************************* JNI functions ***************************************************** +// ************************* JNI functions **************************************************** // called by a java program to get the version number // the function name is constructed from method names in the calling java program extern "C" EXPORT jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass) { - return env->NewStringUTF(_version); + return env->NewStringUTF(g_version); } // called by a java program to format the source code @@ -2398,7 +2597,7 @@ } // Call the Java error handler -void STDCALL javaErrorHandler(int errorNumber, char* errorMessage) +void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage) { jstring errorMessageJava = g_env->NewStringUTF(errorMessage); g_env->CallVoidMethod(g_obj, g_mid, errorNumber, errorMessageJava); @@ -2430,39 +2629,33 @@ if (pSourceIn == NULL) { - fpErrorHandler(101, (char*)"No pointer to source input."); + fpErrorHandler(101, "No pointer to source input."); return NULL; } if (pOptions == NULL) { - fpErrorHandler(102, (char*)"No pointer to AStyle options."); + fpErrorHandler(102, "No pointer to AStyle options."); return NULL; } if (fpMemoryAlloc == NULL) { - fpErrorHandler(103, (char*)"No pointer to memory allocation function."); + fpErrorHandler(103, "No pointer to memory allocation function."); return NULL; } ASFormatter formatter; + ASOptions options(formatter); vector optionsVector; istringstream opt(pOptions); - _err = new stringstream; - importOptions(opt, optionsVector); + options.importOptions(opt, optionsVector); - parseOptions(formatter, - optionsVector.begin(), - optionsVector.end(), - "Invalid Artistic Style options.\n" - "The following options were not processed:"); + bool ok = options.parseOptions(optionsVector, + "Invalid Artistic Style options:"); - if (_err->str().length() > 0) - fpErrorHandler(210, (char*) _err->str().c_str()); - - delete _err; - _err = NULL; + if (!ok) + fpErrorHandler(210, options.getOptionErrors().c_str()); istringstream in(pSourceIn); ASStreamIterator streamIterator(&in); @@ -2474,6 +2667,15 @@ out << formatter.nextLine(); if (formatter.hasMoreLines()) out << streamIterator.getOutputEOL(); + else + { + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + out << streamIterator.getOutputEOL(); + out << formatter.nextLine(); + } + } } unsigned long textSizeOut = out.str().length(); @@ -2481,55 +2683,58 @@ // pTextOut = NULL; // for testing if (pTextOut == NULL) { - fpErrorHandler(110, (char*)"Allocation failure on output."); + fpErrorHandler(110, "Allocation failure on output."); return NULL; } strcpy(pTextOut, out.str().c_str()); - + assert(formatter.getChecksumDiff() == 0); return pTextOut; } extern "C" EXPORT const char* STDCALL AStyleGetVersion (void) { - return _version; + return g_version; } // ASTYLECON_LIB is defined to exclude "main" from the test programs #elif !defined(ASTYLECON_LIB) -// ************************** main function *************************************************** +// ************************* main function **************************************************** int main(int argc, char** argv) { + // Set the locale. + // Not all compilers support the C++ function locale::global(locale("")); + // For testing on Windows change the "Region and Language" settings. + // Changing setlocale will NOT work since ::GetNumberFormat uses the LCID. + // For testing on Linux change the following setlocale: "fr_FR.UTF-8", "de_DE.UTF-8". + char* localeName = setlocale(LC_ALL, ""); + if (localeName == NULL) + cout << "Cannot set native locale" << endl; + + // create objects ASFormatter formatter; - g_console = new ASConsole; + g_console = new ASConsole(formatter); // process command line and options file // build the vectors fileNameVector, optionsVector, and fileOptionsVector - processReturn returnValue = g_console->processOptions(argc, argv, formatter); - - // check for end of processing - if (returnValue == END_SUCCESS) - return EXIT_SUCCESS; - if (returnValue == END_FAILURE) - { - (*_err) << "Artistic Style has terminated!" << endl; - return EXIT_FAILURE; - } + vector argvOptions; + argvOptions = g_console->getArgvOptions(argc, argv); + g_console->processOptions(argvOptions); // if no files have been given, use cin for input and cout for output if (g_console->fileNameVectorIsEmpty()) { - g_console->formatCinToCout(formatter); + g_console->formatCinToCout(); return EXIT_SUCCESS; } // process entries in the fileNameVector - g_console->processFiles(formatter); + g_console->processFiles(); delete g_console; return EXIT_SUCCESS; } -#endif +#endif // ASTYLE_LIB diff -Nru astyle-1.24/src/astyle_main.h astyle-2.01/src/astyle_main.h --- astyle-1.24/src/astyle_main.h 2010-01-30 19:55:39.000000000 +0000 +++ astyle-2.01/src/astyle_main.h 2010-11-29 17:28:18.000000000 +0000 @@ -31,6 +31,7 @@ // headers //---------------------------------------------------------------------------- +#include #include #include "astyle.h" @@ -59,14 +60,17 @@ #error - Use Microsoft compiler version 6 or higher #endif -//using namespace astyle; +// for mingw BOM, UTF-16, and Unicode functions +#if defined(__MINGW32__) +#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 16)) +#error - Use MinGW compiler version 4 or higher +#endif +#endif + namespace astyle { -// return values for ASConsole -enum processReturn { CONTINUE, END_SUCCESS, END_FAILURE }; - //---------------------------------------------------------------------------- // ASStreamIterator class // typename will be istringstream for GUI and istream otherwise @@ -80,7 +84,7 @@ bool checkForEmptyLine; // function declarations - ASStreamIterator(T *in); + ASStreamIterator(T* in); virtual ~ASStreamIterator(); bool getLineEndChange(int lineEndFormat) const; string nextLine(bool emptyLineWasDeleted); @@ -89,7 +93,9 @@ void saveLastInputLine(); private: - T * inStream; // pointer to the input stream + ASStreamIterator(const ASStreamIterator& copy); // copy constructor not to be imlpemented + ASStreamIterator& operator=(ASStreamIterator&); // assignment operator not to be implemented + T* inStream; // pointer to the input stream string buffer; // current input line string prevBuffer; // previous input line int eolWindows; // number of Windows line endings, CRLF @@ -100,8 +106,8 @@ bool prevLineDeleted; // the previous input line was deleted public: // inline functions - bool compareToInputBuffer(const string &nextLine) const - { return (nextLine == prevBuffer); } + bool compareToInputBuffer(const string& nextLine_) const + { return (nextLine_ == prevBuffer); } const char* getOutputEOL() const { return outputEOL; } bool hasMoreLines() const { return !inStream->eof(); } }; @@ -113,6 +119,7 @@ class ASConsole { private: // variables + ASFormatter& formatter; // reference to the ASFormatter object // command line options bool isRecursive; // recursive option string origSuffix; // suffix= option @@ -126,7 +133,7 @@ bool hasWildcard; // file name includes a wildcard size_t mainDirectoryLength; // directory length to be excluded in displays bool filesAreIdentical; // input and output files are identical - bool lineEndsMixed; // outputhas mixed line ends + bool lineEndsMixed; // output has mixed line ends int linesOut; // number of output lines int filesFormatted; // number of files formatted int filesUnchanged; // number of files unchanged @@ -145,7 +152,7 @@ vector fileName; // files to be processed including path public: - ASConsole() { + ASConsole(ASFormatter& formatterArg) : formatter(formatterArg) { // command line options isRecursive = false; origSuffix = ".orig"; @@ -169,8 +176,10 @@ // functions void convertLineEnds(ostringstream& out, int lineEnd); - void error(const char *why, const char* what) const; - void formatCinToCout(ASFormatter& formatter) const; + void error() const; + void error(const char* why, const char* what) const; + void formatCinToCout() const; + vector getArgvOptions(int argc, char** argv) const; FileEncoding getFileEncoding(ifstream& in) const; bool fileNameVectorIsEmpty(); int getFilesFormatted(); @@ -181,12 +190,14 @@ bool getIsVerbose(); bool getLineEndsMixed(); bool getNoBackup(); + string getNumberFormat(int num, size_t=0) const ; + string getNumberFormat(int num, const char* groupingArg, const char* separator) const; string getOptionsFileName(); bool getOptionsFileRequired(); string getOrigSuffix(); bool getPreserveDate(); - void processFiles(ASFormatter &formatter); - processReturn processOptions(int argc, char** argv, ASFormatter &formatter); + void processFiles(); + void processOptions(vector& argvOptions); void setIsFormattedOnly(bool state); void setIsQuiet(bool state); void setIsRecursive(bool state); @@ -196,9 +207,11 @@ void setOptionsFileRequired(bool state); void setOrigSuffix(string suffix); void setPreserveDate(bool state); - void standardizePath(string &path, bool removeBeginningSeparator=false) const; - bool stringEndsWith(const string &str, const string &suffix) const; + void setProgramLocale(); + void standardizePath(string& path, bool removeBeginningSeparator=false) const; + bool stringEndsWith(const string& str, const string& suffix) const; void updateExcludeVector(string suffixParam); + void verifyCinPeek() const; // for unit testing vector getExcludeVector(); @@ -209,42 +222,65 @@ vector getFileName(); private: + ASConsole& operator=(ASConsole&); // not to be implemented void correctMixedLineEnds(ostringstream& out); - void formatFile(const string &fileName, ASFormatter &formatter); - string getCurrentDirectory(const string &fileName) const; - void getFileNames(const string &directory, const string &wildcard); - void getFilePaths(string &filePath); + void formatFile(const string& fileName_); + string getCurrentDirectory(const string& fileName_) const; + void getFileNames(const string& directory, const string& wildcard); + void getFilePaths(string& filePath); + string getParam(const string& arg, const char* op); void initializeOutputEOL(LineEndFormat lineEndFormat); - bool isPathExclued(const string &subPath); + bool isOption(const string& arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + bool isParamOption(const string& arg, const char* option); + bool isPathExclued(const string& subPath); void printBadEncoding(FileEncoding encoding) const; void printHelp() const; - void printMsg(const string &msg) const; + void printMsg(const string& msg) const; + void printSeparatingLine() const; void printVerboseHeader() const; void printVerboseStats(clock_t startTime) const; - void removeFile(const char* fileName, const char* errMsg) const; + void removeFile(const char* fileName_, const char* errMsg) const; void renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const; void setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL); void sleep(int seconds) const; int waitForRemove(const char* oldFileName) const; - int wildcmp(const char *wild, const char *data) const; - void writeOutputFile(const string &fileName, ostringstream &out) const; + int wildcmp(const char* wild, const char* data) const; + void writeOutputFile(const string& fileName_, ostringstream& out) const; +#ifdef _WIN32 + void displayLastError(); +#endif }; - //---------------------------------------------------------------------------- -// global function declarations +// ASOptions class for options processing // used by both console and library builds //---------------------------------------------------------------------------- -void importOptions(istream &in, vector &optionsVector); -void isOptionError(const string &arg, const string &errorInfo); -bool isParamOption(const string &arg, const char *option); -bool isParamOption(const string &arg, const char *option1, const char *option2); -bool parseOption(astyle::ASFormatter &formatter, const string &arg, const string &errorInfo); - -template -bool parseOptions(astyle::ASFormatter &formatter, const ITER &optionsBegin, - const ITER &optionsEnd, const string &errorInfo); +class ASOptions +{ + public: + ASOptions(ASFormatter& formatterArg) : formatter(formatterArg) {} + string getOptionErrors(); + void importOptions(istream& in, vector &optionsVector); + bool parseOptions(vector &optionsVector, const string& errorInfo); + + private: + // variables + ASFormatter& formatter; // reference to the ASFormatter object + stringstream optionErrors; // option error messages + + // functions + ASOptions& operator=(ASOptions&); // not to be implemented + string getParam(const string& arg, const char* op); + string getParam(const string& arg, const char* op1, const char* op2); + bool isOption(const string arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + void isOptionError(const string& arg, const string& errorInfo); + bool isParamOption(const string& arg, const char* option); + bool isParamOption(const string& arg, const char* option1, const char* option2); + void parseOption(const string& arg, const string& errorInfo); +}; } // end of namespace astyle @@ -254,7 +290,7 @@ //---------------------------------------------------------------------------- #ifdef ASTYLE_JNI -void STDCALL javaErrorHandler(int errorNumber, char* errorMessage); +void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage); char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded); // the following function names are constructed from method names in the calling java program extern "C" EXPORT