diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..11dfa6b --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 by Jim Pattee . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/doc/astyle.html b/doc/astyle.html index 1212759..5ccebc0 100644 --- a/doc/astyle.html +++ b/doc/astyle.html @@ -1,6 +1,6 @@ - + - + Artistic Style @@ -16,26 +16,23 @@ -

Artistic Style 2.05

+

Artistic Style 2.06

A Free, Fast, and Small Automatic Formatter
@@ -45,26 +42,19 @@

Contents

- General Information -

+ General Information

- Quick Start -

+ Quick Start

- Usage -

+ Usage

- Options -

+ Options

- Options File -

+ Options File

- Disable Formatting -

+ Disable Formatting

- Bracket Style Options -

+ Bracket Style Options

default bracket style    style=allman    @@ -80,30 +70,24 @@ style=1tbs    style=google    style=pico    - style=lisp    -

+ style=lisp   

- Tab Options -

+ Tab Options

default indent    indent=spaces    indent=tab    indent=force‑tab    - --indent=force‑tab‑x    -

+ --indent=force‑tab‑x   

- Bracket Modify Options -

+ Bracket Modify Options

attach‑namespaces    attach‑classes    attach‑inlines    - attach‑extern‑c    -

+ attach‑extern‑c   

- Indentation Options -

+ Indentation Options

indent‑classes    indent‑modifiers    @@ -119,12 +103,12 @@ max‑instatement‑indent   

- Padding Options -

+ Padding Options

break‑blocks    break‑blocks=all    pad‑oper    + pad‑comma    pad‑paren    pad‑paren‑out    pad‑first‑paren‑out    @@ -134,11 +118,9 @@ delete‑empty‑lines    fill‑empty‑lines    align‑pointer    - align‑reference    -

+ align‑reference   

- Formatting Options -

+ Formatting Options

break‑closing‑brackets    break‑elseifs    @@ -152,20 +134,18 @@ remove‑comment‑prefix    max‑code‑length    break‑after‑logical    - mode    -

+ mode   

- Objective‑C Options -

+ Objective‑C Options

- align‑method‑colon    pad‑method‑prefix    unpad‑method‑prefix    - pad‑method‑colon    -

+ pad‑return‑type    + unpad‑return‑type    + align‑method‑colon    + pad‑method‑colon   

- Other Options    -

+ Other Options   

suffix    suffix=none    recursive    @@ -178,11 +158,9 @@ verbose    formatted    quiet    - lineend    -

+ lineend   

- Command Line Only -

+ Command Line Only

options    options=none    @@ -190,11 +168,9 @@ version    help    html    - html=    -

+ html=   

-   -

+  


@@ -205,16 +181,14 @@

Line endings in the formatted file will be the same as the input file. If there are mixed line endings the most - frequent occurrence will be used. There is also an option to specify or change the line endings. -

+ frequent occurrence will be used. There is also an option to specify or change the line endings.

File Type

Artistic Style will determine the file type from the file extension. The extension ".java" indicates a Java file, and ".cs" indicates a C# file. Everything else is a C type file (C, C++, C++/CLI, or Objective-C). If you are - using a non-standard file extension for Java or C#, use one of the --mode= options. -

+ using a non-standard file extension for Java or C#, use one of the --mode= options.

Wildcards and Recursion

@@ -223,8 +197,7 @@ If a shell is used it should pass the wildcards to Artistic Style instead of resolving them first. For Linux use double quotes around paths whose file name contains wildcards. For Windows use double quotes around paths whose file name contains spaces. The recursive option in the - Other Options section contains information on recursive processing. -

+ Other Options section contains information on recursive processing.

File Names

@@ -233,38 +206,33 @@ is created with an .orig appended to the original file name. (This can be set to a different string by the option --suffix=, or suppressed altogether by the options -n or --suffix=none). Thus, after indenting SourceFile.cpp the indented file will - be named SourceFile.cpp, while the original pre-indented file will be renamed to SourceFile.cpp.orig. -

+ be named SourceFile.cpp, while the original pre-indented file will be renamed to + SourceFile.cpp.orig.

Internationalization

- Artistic Style has been internationalized to process files and directories in any language. -

+ Artistic Style has been internationalized to process files and directories in any language.

It has also been translated into several languages. The translation to use is determined from the User Locale for Windows and the LANG environment variable for other systems. The translation will be done automatically from these settings. If no translation is available it will default to English. There is an ascii option to use English - instead of the system language. -

+ instead of the system language.

The source code for the translations is at the end of ASLocalizer.cpp in the form of an English‑Translation pair. If you make corrections to a translation, send the source as a bug report and it will be included in the - next release. -

+ next release.

To add a new language, add a new translation class to ASLocalizer.h. Add the English‑Translation pair to the constructor in ASLocalizer.cpp. Update the WinLangCode array and add the language code to the function setTranslationClass(). The ASLocalizer.cpp program contains comments that give web pages for obtaining the LCIDs and language codes. - Send the source code as a bug report and it will be included in the next release. -

+ Send the source code as a bug report and it will be included in the next release.

Other Considerations

The names of special characters used in programming vary by region. The terminology used by Artistic Style, - followed by other common names, is: -

+ followed by other common names, is:

brackets { } ‑ also called braces, curly brackets, or curly braces.
parens ( ) ‑ also called parentheses, brackets, round brackets, circle brackets, or soft brackets.
@@ -273,17 +241,19 @@ or chevrons.

- Artistic Style can format standard class library statements such as Open GL, wxWidgets, Qt, and MFC. -

+ Visual Studio, and possibly other development environments, has an Edit option "Align Assignments" that will align + assignment operators across multiple lines. There is also an extension named "Code alignment" that will align + the code on other items as well. Formatting with these options and extensions can be used with Artistic Style. + The space padding will be maintained and the alignment will be preserved.

+

+ Artistic Style can format standard class library statements such as Open GL, wxWidgets, Qt, and MFC.

Embedded assembler language is formatted correctly. This includes extended assembly and Microsoft specific assembler - lines and blocks. -

+ lines and blocks.

Artistic Style can format embedded SQL statements. The SQL formatting will be maintained as long as the standard hanging indent format is used. If the "exec sql" statement is indented more than the following statements, the - SQL will be aligned in a single column. -

+ SQL will be aligned in a single column.

Unicode files encoded as UTF‑16, both big and little endian, will be formatted. The files must begin with a byte order mark (BOM) to be recognized. Files encoded as UTF‑32 will be rejected. Some compilers do not @@ -292,18 +262,16 @@ command line is "iconv ‑f  UTF‑16 ‑t UTF‑8 < filein.cpp > fileout.cpp. Visual Studio can convert the files from the "File > Advanced Save Options" menu. Then select encoding "Unicode (UTF‑8 with signature) - Codepage 65001". There are other development environments and text editors, such as SciTE, that - can convert files to UTF‑8. -

+ can convert files to UTF‑8.

Embedded statements that are multiple-line and are NOT in a C-type format, such as Python, are usually mal-formatted (a C-type format has blocks enclosed by brackets and statements terminated by a semi-colon). Macros that define functions may cause the following code to be mal-formatted because the macro is missing the brackets and semi-colons from the definition. If you have source code with these types of statements, exclude them with the - exclude=#### option described in the Other Options section. -

+ exclude=#### option described in the Other Options + section.

-   -

+  


@@ -311,32 +279,23 @@

Quick Start

- If you have never used Artistic Style there are a couple of ways to start. -

+ If you have never used Artistic Style there are a couple of ways to start.

- One is to run it with no options at all. This will use the - default bracket - style - , 4 spaces per indent, and no formatting changes. This will break the brackets for one + One is to run it with no options at all. This will use the default bracket + style, 4 spaces per indent, and no formatting changes. This will break the brackets for one line blocks and will break one line statements. To change this use the option keep-one-line-blocks and/or keep-one-line-statements described in the - Formatting Options section -

+ Formatting Options section

- Another way is to use one of the bracket styles described in the - Bracket Style - Options - section. Select one with a bracket formatting style you like. If no indentation option is set, the - default option of 4 spaces will be used. These options also break one line blocks and one line statements as - described above. -

+ Another way is to use one of the bracket styles described in the Bracket Style + Options section. Select one with a bracket formatting style you like. If no indentation option is set, + the default option of 4 spaces will be used. These options also break one line blocks and one line statements + as described above.

- Once you are familiar with the options you can customize the format to your personal preference. -

+ Once you are familiar with the options you can customize the format to your personal preference.

-   -

+  


@@ -345,45 +304,41 @@

Artistic style is a console program that receives information from the command line. The format of the command - line is: -

+ line is:

astyle  [OPTIONS]  SourceFile1  SourceFile2  SourceFile3  [ . . . ]
 

The block parens [ ] indicate that more than one option or more than one file name can be entered. They are NOT - actually included in the command. For the options format see the following Options section. -

+ actually included in the command. For the options format see the following Options section.

-

-   Example to format a single file: -

+

+ Example to format a single file:

astyle  --style=allman  /home/user/project/foo.cpp
 
-

-   Example to format all .cpp and .h files recursively: -

+

+ Example to format all .cpp and .h files recursively:

astyle  --style=allman --recursive  /home/user/project/*.cpp  /home/user/project/*.h
 

- Another option will format a single file and change the name: -

-
astyle  [OPTIONS] < OriginalSourceFile > BeautifiedSourceFile
+        The < and > characters may be used to redirect the files into standard input (stdin) and out of standard output
+        (stdout) - don't forget them! With this option only one file at a time can be formatted. Wildcards are not 
+        recognized, there are no console messages, and a backup is not created. On Windows the output will always have
+        Windows line ends.

+
+

+ Example of redirection option to format a single file and change the name:

+
astyle --style=allman < OriginalSourceFile > BeautifiedSourceFile
 
-

- This option can be used to display the formatted file without updating: -

-
astyle  [OPTIONS] < OriginalSourceFile | less
+    
+
+

+ The redirection option may be used to display the formatted file without updating:

+
astyle --style=allman < OriginalSourceFile | less
 
+

- The < and > characters are used - to redirect the files into standard input (cin) and out of standard output (cout) - don't forget them! With this - option only one file at a time can be formatted. Wildcards are not recognized, there are no console messages, - and a backup is not created. On Windows the output will always have Windows line ends. -

-

-   -

+  


@@ -392,28 +347,23 @@

Not specifying any options will result in the default bracket style, - 4 spaces per indent, and no formatting changes. -

+ 4 spaces per indent, and no formatting changes.

- Options may be written in two different ways. -

+ Options may be written in two different ways.

Long options

These options start with '--', and must be written one at a time.
- (Example: '--style=allman --indent=spaces=4') -

+ (Example: '--style=allman --indent=spaces=4')

Short Options

These options start with a single '-', and may be concatenated together.
- (Example: '-bps4' is the same as writing '-b -p -s4'.) -

+ (Example: '-bps4' is the same as writing '-b -p -s4'.)

-   -

+  


@@ -421,24 +371,19 @@

Options File

- An OPTIONAL default options file may be used to supplement or replace the command line options.  -

+ An OPTIONAL default options file may be used to supplement or replace the command line options. 

- Example of a default options file: -

+ Example of a default options file:

# this line is a comment
 --style=allman      # this is a line-end comment
@@ -462,77 +406,60 @@ indent-switches     # cannot do this on the command line
     

-   -

+  


-

- Disable Formatting -

+

Disable Formatting

- Formatting and indenting can be disabled with comment tags inserted in the source code. -

+ Formatting and indenting can be disabled with comment tags inserted in the source code.

-

- Disable Block -

+

Disable Block

Blocks of code can be disabled using "off" and "on" tags. The tags are included in the source file as comments. The comment may be a C comment (/* ... */) or a C++ line comment (//). The tag must be included in a single line comment. If the comment exceeds one line the indent tag will be ignored. Additional information - can be included with the tag. -

+ can be included with the tag.

The beginning tag is "*INDENT-OFF*" and the ending tag is "*INDENT-ON*". They may be used anywhere in the program with the following condition; parsing is partially disabled between the tags. Disabling partial statements may result in incorrect formatting after the ending tag. If this happens expand - the tags to include additional code. -

+ the tags to include additional code.

- The following retains the format of a preprocessor define: -

-
// *INDENT-OFF*
+            The following retains the format of a preprocessor define:

+
// *INDENT-OFF*
 #define FOO_DECLARE_int32_(name) \
         FOO_API_ extern ::Int32 FOO_FLAG(name)
-// *INDENT-ON*
+// *INDENT-ON*
-

- Disable Line -

+

Disable Line

Artistic Style cannot always determine the usage of symbols with more than one meaning. For example an asterisk (*) can be multiplication, a pointer, or a pointer dereference. The "&" and "&&" symbols are a similar - problem. -

+ problem.

If a symbol is being padded incorrectly, padding it manually may fix the problem. If it is still being padded incorrectly, then disabling the formatting may be necessary. To avoid having to use the "disable block" - tags above, a single line disable is available. -

+ tags above, a single line disable is available.

A line-end comment tag "*NOPAD* will disable the "pad-oper", "align-pointer", and "align-reference" options. Parsing does NOT stop and all other formatting will be applied to the line. The tag applies to the - one line only. -

+ one line only.

- The following prevents the operator padding from - changing: -

+ The following prevents the operator padding from changing:

size_t foo = (unsigned int) -1;  // *NOPAD*

-   -

+  


@@ -541,114 +468,99 @@ indent-switches # cannot do this on the command line Bracket Style options define the bracket style to use. All options default to 4 spaces per indent, indented with - spaces. - By default, none of the styles indent namespaces. Other indentations are indicated in the individual style + spaces. By default, none of the styles indent namespaces. Other indentations are indicated in the individual style description. All options will break the brackets for one line blocks and will break one line statements. To change - this - use the option keep-one-line-blocks and/or - keep-one-line-statements - described in the Formatting Options section -

+ this use the option keep-one-line-blocks and/or + keep-one-line-statements described in the Formatting Options + section.

-   -

+  

default bracket style
If no bracket style is requested, the default bracket style will be used. The opening brackets are not changed - and the closing brackets will be broken from the preceding line. There are a few exceptions to this. -

+ and the closing brackets will be broken from the preceding line. There are a few exceptions to this.

-   -

+  

--style=allman / --style=bsd / --style=break / -A1
- Allman style uses broken brackets. -

+ Allman style uses broken brackets.

int Foo(bool isBar)
 {
     if (isBar)
-        {
+    {
         bar();
         return 1;
-        }
+    }
     else
         return 0;
-}        
-
-
-

-   -

-

- --style=java / --style=attach / -A2
- Java style uses attached brackets. -

-
-
int Foo(bool isBar) {
-    if (isBar) {
-        bar();
-        return 1;
-        } else
-        return 0;
 }
 

-   -

+  

+

+ --style=java / --style=attach / -A2
+ Java style uses attached brackets.

+
+
int Foo(bool isBar) {
+    if (isBar) {
+        bar();
+        return 1;
+    } else
+        return 0;
+}
+
+
+

+  

--style=kr / --style=k&r / --style=k/r / -A3
Kernighan & Ritchie style uses linux brackets. Opening brackets are broken from namespaces, classes, and function definitions. Brackets are attached to everything else including statements within a function, arrays, structs, - and enums. -

+ and enums.

Using the k&r option may cause problems because of the &. This can be resolved by enclosing the k&r - in quotes (e.g. ‑‑style="k&r") or by using one of the alternates ‑‑style=kr or ‑‑style=k/r. -

+ in quotes (e.g. ‑‑style="k&r") or by using one of the alternates ‑‑style=kr or + ‑‑style=k/r.

-
int Foo(bool isBar) 
+        
int Foo(bool isBar)
 {
     if (isBar) {
         bar();
         return 1;
-        } else
+    } else
         return 0;
 }
 

-   -

+  

--style=stroustrup / -A4
Stroustrup style uses stroustrup brackets. Brackets are broken from function definitions only. Brackets are attached to everything else including namespaces, classes, and statements within a function, arrays, structs, and enums. - This style frequently is used with an indent of 5 spaces. -

+ This style frequently is used with an indent of 5 spaces.

-
int Foo(bool isBar) 
+        
int Foo(bool isBar)
 {
-     if (isBar) {
-          bar();
-          return 1;
-        } else
-          return 0;
+    if (isBar) {
+        bar();
+        return 1;
+    } else
+        return 0;
 }
 

-   -

+  

--style=whitesmith / -A5
Whitesmith style uses broken, indented brackets. Switch blocks and class blocks are indented to prevent a 'hanging - indent' with following case statements and C++ class modifiers (public, private, protected).  -

+ indent' with following case statements and C++ class modifiers (public, private, protected). 

-
int Foo(bool isBar) 
-        {
+        
int Foo(bool isBar)
+    {
     if (isBar)
         {
         bar();
@@ -656,19 +568,17 @@ indent-switches     # cannot do this on the command line}
     else
         return 0;
-        }
+    }
 

-   -

+  

--style=vtk / -A15
VTK (Visualization Toolkit) style uses broken, indented brackets, except for the opening bracket. Switch blocks - are indented to prevent a 'hanging indent' with following case statements.  -

+ are indented to prevent a 'hanging indent' with following case statements. 

-
int Foo(bool isBar) 
+        
int Foo(bool isBar)
 {
     if (isBar)
         {
@@ -681,13 +591,11 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--style=banner / -A6
Banner style uses attached, indented brackets. Switch blocks and class blocks are indented to prevent a 'hanging - indent' with following case statements and C++ class modifiers (public, private, protected).  -

+ indent' with following case statements and C++ class modifiers (public, private, protected). 

int Foo(bool isBar) {
     if (isBar) {
@@ -696,48 +604,42 @@ indent-switches     # cannot do this on the command line}
     else
         return 0;
-        }
+    }
 

-   -

+  

--style=gnu / -A7
GNU style uses broken brackets and indented blocks. This style frequently is used with - an indent of 2 spaces. -

+ an indent of 2 spaces.

Extra indentation is added to blocks within a function. The opening bracket for namespaces, classes, - and functions is not indented. -

+ and functions is not indented.

int Foo(bool isBar)
 {
-  if (isBar)
+    if (isBar)
         {
-      bar();
-      return 1;
+            bar();
+            return 1;
         }
-  else
-    return 0;
+    else
+        return 0;
 }
 

-   -

+  

--style=linux / --style=knf / -A8
Linux style uses linux brackets. Opening brackets are broken from namespace, class, and function definitions. Brackets are attached to everything else including statements within a function, arrays, structs, and enums. Minimum conditional indent is one-half indent. If you want a different minimum conditional indent use the K&R style instead. This style works best with a large indent. It frequently is used with an - indent of 8 spaces. -

+ indent of 8 spaces.

- Also known as Kernel Normal Form (KNF) style, this is the style used in the Linux kernel. -

+ Also known as Kernel Normal Form (KNF) style, this is the style used in the Linux kernel.

int Foo(bool isBar)
 {
@@ -750,97 +652,87 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--style=horstmann / -A9
- Horstmann style uses run-in brackets. Brackets are broken and allow run-in statements. - Switches are indented to allow a run-in to the opening switch block. This style frequently is used with an indent - of 3 spaces. -

+ Horstmann style uses run-in brackets. Brackets are broken and allow run-in statements. Switches are indented to + allow a run-in to the opening switch block. This style frequently is used with an indent of 3 spaces.

int Foo(bool isBar)
-{  if (isBar)
-        {  bar();
-      return 1;
-        } else
-      return 0;
+{   if (isBar)
+    {   bar();
+        return 1;
+    }
+    else
+        return 0;
 }
 

-   -

+  

--style=1tbs / --style=otbs / -A10
"One True Brace Style" uses linux brackets and adds brackets to unbracketed one line conditional statements. Opening brackets are broken from namespaces, classes, and function definitions. Brackets are attached - to everything else including statements within a function, arrays, structs, and enums.  -

+ to everything else including statements within a function, arrays, structs, and enums. 

In the following example brackets have been added to the "return 0;" statement. The option - ‑‑add‑one‑line‑brackets can also be used with this style. -

+ ‑‑add‑one‑line‑brackets can also be used with this style.

int Foo(bool isBar)
 {
     if (isFoo) {
         bar();
         return 1;
-        } else {
+    } else {
         return 0;
-        }
+    }
 }
 

-   -

+  

--style=google / -A14
Google style uses attached brackets and indented class access modifiers. See the indent-modifiers - option for an example of the indented modifiers format. This style frequently is used with an indent of 2 spaces. -

+ option for an example of the indented modifiers format. This style frequently is used with an indent of + 2 spaces.

int Foo(bool isBar) {
     if (isBar) {
         bar();
         return 1;
-        } else
+    } else
         return 0;
 }
 

-   -

+  

--style=pico / -A11
Pico style uses run-in brackets and attached closing brackets. Opening brackets are broken and allow run-in statements. The closing bracket is attached to the last line in the block. Switches are indented to allow a run-in to the opening switch block. The style implies keep-one-line-blocks and keep-one-line-statements. If add-brackets is used they will be added as one-line brackets. This style frequently is used with an indent - of 2 spaces. -

+ of 2 spaces.

int Foo(bool isBar)
-{  if (isBar)
-        {  bar();
-      return 1; }    
+{   if (isBar)
+    {   bar();
+        return 1; }
     else
-      return 0; }
+        return 0; }
 

-   -

+  

--style=lisp / --style=python / -A12
Lisp style uses attached opening and closing brackets. Opening brackets are attached at the end of the statement. The closing bracket is attached to the last line in the block. The style implies keep-one-line-statements but NOT keep-one-line-blocks. This style does not support one-line brackets. If add-one-line-brackets is used - they will be added as multiple-line brackets. -

+ they will be added as multiple-line brackets.

int Foo(bool isBar) {
     if (isBar) {
@@ -851,8 +743,7 @@ indent-switches     # cannot do this on the command line
     

-   -

+  


@@ -861,19 +752,15 @@ indent-switches # cannot do this on the command line The following examples show whitespace characters. A space is indicated with a . (dot), a tab - is indicated by a > (greater than). -

+ is indicated by a > (greater than).

default indent
- If no indentation option is set, the default option of 4 spaces will be used (e.g. - -s4 + If no indentation option is set, the default option of 4 spaces will be used (e.g. -s4 --indent=spaces=4 - ). -

+ ).

- with default values: -

+ with default values:

void Foo() {
 ....if (isBar1
 ............&& isBar2)    // indent of this line can be changed with min-conditional-indent
@@ -882,19 +769,16 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--indent=spaces / --indent=spaces=# / -s#
- Indent using # spaces per indent (e.g. -s3 - --indent=spaces=3 + Indent using # spaces per indent (e.g. -s3 --indent=spaces=3 ). # must be between 2 and 20. Not specifying # will result in a default of - 4 spaces per indent. -

+ 4 spaces per indent.

- with indent=spaces=3 -

+ with indent=spaces=3

void Foo() {
 ...if (isBar1
 .........&& isBar2)    // indent of this line can be changed with min-conditional-indent
@@ -903,19 +787,16 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--indent=tab / --indent=tab=# / -t / -t#
Indent using tabs for indentation, and spaces for continuation line alignment. This ensures that the code is displayed correctly  regardless of the viewer’s tab size. Treat each indent as # spaces (e.g. -t6 / --indent=tab=6). - # must be between 2 and 20. If no # is set, treats indents as 4 spaces. -

+ # must be between 2 and 20. If no # is set, treats indents as 4 spaces.

- with indent=tab: -

+ with indent=tab:

void Foo() {
 >   if (isBar1
 >   ........&& isBar2)    // indent of this line can be changed with min-conditional-indent
@@ -923,8 +804,7 @@ indent-switches     # cannot do this on the command line}
 

- with style=linux, indent=tab=8: -

+ with style=linux, indent=tab=8:

void Foo()
 {
 >       if (isBar1
@@ -934,47 +814,40 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--indent=force-tab / --indent=force-tab=# / -T / -T#
Indent using all tab characters, if possible. If a continuation line is not an even number of tabs, spaces will be added at the end. Treat each tab as # spaces (e.g. -T6 / --indent=force-tab=6). # must be between - 2 and 20. If no # is set, treats tabs as 4 spaces. -

+ 2 and 20. If no # is set, treats tabs as 4 spaces.

- with indent=force-tab: -

+ with indent=force-tab:

void Foo() {
->   if (isBar1
->   >   >   && isBar2)    // indent of this line can be changed with min-conditional-indent
->   >   bar();
+>   if (isBar1
+>   >   >   && isBar2)    // indent of this line can be changed with min-conditional-indent
+>   >   bar();
 }
 

-   -

+  

- - --indent=force-tab-x / --indent=force-tab-x=# / -xT / -xT# + --indent=force-tab-x / --indent=force-tab-x=# / -xT / -xT#
This force-tab option allows the tab length to be set to a length that is different than the indent length. This may cause the indentation to be a mix of both tabs and spaces. Tabs will be used to indent, if - possible. If a tab indent cannot be used, spaces will be used instead. -

+ possible. If a tab indent cannot be used, spaces will be used instead.

This option sets the tab length. Treat each tab as # spaces (e.g. -xT6 / --indent=force-tab-x=6). # must be between 2 and 20. If no # is set, treats tabs as 8 spaces. To change the indent length from the default - of 4 spaces the option "indent=force-tab" must also be used. -

+ of 4 spaces the option "indent=force-tab" must also be used.

- with indent=force-tab-x (default tab length of 8 and default indent length of 4): -

+ with indent=force-tab-x (default tab length of 8 and default indent length of 4):

void Foo() {
 ....if (isBar1
 >       ....&& isBar2)    // indent of this line can be changed with min-conditional-indent
@@ -983,8 +856,7 @@ indent-switches     # cannot do this on the command line
     

-   -

+  


@@ -993,45 +865,37 @@ indent-switches # cannot do this on the command line --attach-namespaces / -xn
- Attach brackets to a namespace statement. This is done regardless of the bracket style being used. -

+ Attach brackets to a namespace statement. This is done regardless of the bracket style being used.

- the bracket is always attached to a namespace statement: -

+ the bracket is always attached to a namespace statement:

namespace FooName {
 ...
 }
 

-   -

+  

--attach-classes / -xc
- Attach brackets to a class statement. This is done regardless of the bracket style being used. -

+ Attach brackets to a class statement. This is done regardless of the bracket style being used.

- the bracket is always attached to a class statement: -

+ the bracket is always attached to a class statement:

class FooClass {
 ...
 };
 

-   -

+  

--attach-inlines / -xl
- Attach brackets to class and struct inline function definitions. This is not done for run-in type brackets (Horstmann - and Pico styles). This option is effective for C++ files only. -

+ Attach brackets to class and struct inline function definitions. This is not done for run-in type brackets + (Horstmann and Pico styles). This option is effective for C++ files only.

- all brackets are always attached to class and struct inline function definitions: -

+ all brackets are always attached to class and struct inline function definitions:

class FooClass
 {
     void Foo() {
@@ -1041,36 +905,30 @@ indent-switches     # cannot do this on the command line
     

-   -

+  

--attach-extern-c / -xk
Attach brackets to a bracketed extern "C" statement. This is done regardless of the bracket style being used. - This option is effective for C++ files only. -

+ This option is effective for C++ files only.

An extern "C" statement that is part of a function definition is formatted according to the requested bracket style. Bracketed extern "C" statements are unaffected by the bracket style and this option is the only way to - change them. -

+ change them.

- this option attaches brackets to a bracketed extern "C" statement: -

+ this option attaches brackets to a bracketed extern "C" statement:

#ifdef __cplusplus
 extern "C" {
 #endif
 

- but function definitions are formatted according to the requested bracket style: -

+ but function definitions are formatted according to the requested bracket style:

extern "C" EXPORT void STDCALL Foo()
 {}
 

-   -

+  


@@ -1081,8 +939,7 @@ extern "C" { --indent-classes / -C
Indent 'class' and 'struct' blocks so that the entire block is indented. The struct blocks are indented only if an access modifier, 'public:', 'protected:' or 'private:', - is declared somewhere in the struct. This option is effective for C++ files only. -

+ is declared somewhere in the struct. This option is effective for C++ files only.

class Foo
 {
@@ -1092,8 +949,7 @@ public:
 };
 

- becomes: -

+ becomes:

class Foo
 {
     public:
@@ -1103,14 +959,12 @@ public:
 

-   -

+  

--indent-modifiers / -xG
Indent 'class' and 'struct' access modifiers, 'public:', 'protected:' and 'private:', one half indent. The rest of the class is not indented. This option is effective - for C++ files only. If used with indent‑classes this option will be ignored. -

+ for C++ files only. If used with indent‑classes this option will be ignored.

class Foo
 {
@@ -1120,8 +974,7 @@ public:
 };
 

- becomes: -

+ becomes:

class Foo
 {
   public:
@@ -1131,19 +984,18 @@ public:
 

-   -

+  

--indent-switches / -S
Indent 'switch' blocks so that the 'case X:' statements are indented in the switch - block. The entire case block is indented. -

+ block. The entire case block is indented.

switch (foo)
 {
 case 1:
     a += 1;
     break;
+
 case 2:
 {
     a += 2;
@@ -1152,50 +1004,49 @@ case 2:
 }
 

- becomes: -

+ becomes:

switch (foo)
 {
     case 1:
         a += 1;
         break;
+
     case 2:
-        {
+    {
         a += 2;
         break;
-        }
+    }
 }
 

-   -

+  

--indent-cases / -K
Indent 'case X:' blocks from the 'case X:' headers. Case statements not enclosed in - blocks are NOT indented. -

+ blocks are NOT indented.

switch (foo)
 {
     case 1:
         a += 1;
         break;
+
     case 2:
-        {
+    {
         a += 2;
         break;
-        }
+    }
 }
 

- becomes: -

+ becomes:

switch (foo)
 {
     case 1:
         a += 1;
         break;
+
     case 2:
         {
             a += 2;
@@ -1205,12 +1056,10 @@ case 2:
 

-   -

+  

--indent-namespaces / -N
- Add extra indentation to namespace blocks. This option has no effect on Java files. -

+ Add extra indentation to namespace blocks. This option has no effect on Java files.

namespace foospace
 {
@@ -1223,27 +1072,24 @@ class Foo
 }
 

- becomes: -

+ becomes:

namespace foospace
 {
     class Foo
-        {
+    {
         public:
             Foo();
             virtual ~Foo();
-        };
+    };
 }
 

-   -

+  

--indent-labels / -L
Add extra indentation to labels so they appear 1 indent less than the current indentation, rather than being flushed - to the left (the default). -

+ to the left (the default).

void Foo() {
     while (isFoo) {
@@ -1256,8 +1102,7 @@ error:
 }
 

- becomes (with indented 'error:'): -

+ becomes (with indented 'error:'):

void Foo() {
     while (isFoo) {
         if (isFoo)
@@ -1265,33 +1110,31 @@ error:
         ... 
     error:
         ...
-        }        
+        }
 }
 

-   -

+  

--indent-preproc-block / -xW
Indent preprocessor blocks at bracket level zero, and immediately within a namespace. There are restrictions on what will be indented. Blocks within methods, classes, arrays, etc, will not be indented. Blocks containing brackets - or multi-line define statements will not be indented. Without this option the preprocessor block is not indented. -

+ or multi-line define statements will not be indented. Without this option the preprocessor block is not + indented.

#ifdef _WIN32
-#include <windows.h>  
+#include <windows.h>
 #ifndef NO_EXPORT
 #define EXPORT
 #endif
 #endif
 

- becomes: -

+ becomes:

#ifdef _WIN32
-    #include <windows.h> 
+    #include <windows.h>
     #ifndef NO_EXPORT
         #define EXPORT
     #endif
@@ -1299,34 +1142,29 @@ error:
 

-   -

+  

--indent-preproc-define / -w
Indent multi-line preprocessor definitions ending with a backslash. Should be used with --convert-tabs for proper results. Does a pretty good job, but cannot perform miracles in obfuscated preprocessor definitions. Without this - option the preprocessor statements remain unchanged. -

+ option the preprocessor statements remain unchanged.

#define Is_Bar(arg,a,b) \
 (Is_Foo((arg), (a)) \
 || Is_Foo((arg), (b)))
 

- becomes: -

+ becomes:

#define Is_Bar(arg,a,b) \
     (Is_Foo((arg), (a)) \
      || Is_Foo((arg), (b)))
 

-   -

+  

--indent-preproc-cond / -xw
- Indent preprocessor conditional statements to the same level as the source code. -

+ Indent preprocessor conditional statements to the same level as the source code.

        isFoo = true;
 #ifdef UNICODE
@@ -1335,8 +1173,7 @@ error:
         text = buff;
 #endif

- becomes: -

+ becomes:

        isFoo = true;
         #ifdef UNICODE
         text = wideBuff;
@@ -1346,13 +1183,12 @@ error:
 

-   -

+  

--indent-col1-comments / -Y
- 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. -

+ Indent C++ comments beginning in column one. By default C++ comments beginning in column one are + assumed to be commented‑out code and not indented. This option will allow the comments to be indented with + the code.

void Foo()\n"
 {
@@ -1362,19 +1198,17 @@ error:
 }
 

- becomes: -

+ becomes:

void Foo()\n"
 {
-        // comment
+    // comment
     if (isFoo)
         bar();
 }
 

-   -

+  

--min-conditional-indent=# / -m#
Set the minimal indent that is added when a header is built of multiple lines. This indent helps to easily separate @@ -1386,13 +1220,13 @@ error: 1 - indent at least one additional indent.
2 - indent at least two additional indents.
3 - indent at least one-half an additional indent. This is intended for large indents (e.g. 8).
- The default value is 2, two additional indents. -

+ The default value is 2, two additional indents.

// default setting makes this non-bracketed code clear
 if (a < b
         || c > d)
     foo++;
+
 // but creates an exaggerated indent in this bracketed code
 if (a < b
         || c > d)
@@ -1401,12 +1235,13 @@ if (a < b
 }
 

- becomes (when setting --min-conditional-indent=0): -

+ becomes (when setting + --min-conditional-indent=0):

// setting makes this non-bracketed code less clear
 if (a < b
     || c > d)
     foo++;
+
 // but makes this bracketed code clearer
 if (a < b
     || c > d)
@@ -1416,39 +1251,36 @@ if (a < b
 

-   -

+  

--max-instatement-indent=# / -M#
Set the  maximum of # spaces to indent a continuation line. The - # - indicates a number of columns and must not be greater than 120. - If no # is set, the default value of 40 will be - used. A maximum of less than two indent lengths will be ignored. This option will prevent continuation lines from - extending too far to the right. Setting a larger value will allow the code to be extended further to the right. -

+ #
indicates a number of columns and must not be less than 40 nor + greater than 120. If no value is set, the default value of 40 will be + used. This option will prevent continuation lines from extending too far to the right. Setting a larger value + will allow the code to be extended further to the right.

fooArray[] = { red,
          green,
          blue };
+
 fooFunction(barArg1,
          barArg2,
          barArg3);
 

- becomes (with larger value): -

+ becomes (with larger value):

fooArray[] = { red,
                green,
                blue };
+
 fooFunction(barArg1,
             barArg2,
             barArg3);
 

-   -

+  


@@ -1457,8 +1289,8 @@ fooFunction(barArg1,

--break-blocks / -f
- Pad empty lines around header blocks (e.g. 'if', 'for', 'while'...). -

+ Pad empty lines around header blocks (e.g. 'if', 'for', + 'while'...).

isFoo = true;
 if (isFoo) {
@@ -1469,25 +1301,24 @@ if (isFoo) {
 isBar = false;
 

- becomes: -

+ becomes:

isFoo = true;
+
 if (isFoo) {
     bar();
 } else {
     anotherBar();
 }
+
 isBar = false;
 

-   -

+  

--break-blocks=all / -F
Pad empty lines around header blocks (e.g. 'if', 'for', 'while'...). Treat - closing header blocks (e.g. 'else', 'catch') as stand-alone blocks. -

+ closing header blocks (e.g. 'else', 'catch') as stand-alone blocks.

isFoo = true;
 if (isFoo) {
@@ -1498,82 +1329,89 @@ if (isFoo) {
 isBar = false;
 

- becomes: -

+ becomes:

isFoo = true;
+
 if (isFoo) {
     bar();
-    
+
 } else {
     anotherBar();
 }
+
 isBar = false;
 

-   -

+  

- --pad-oper / -p -
- 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. -

+ --pad-oper / -p
+ Insert space padding around operators. This will also pad commas. 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.

if (foo==2)
     a=bar((b-c)*a,d--);
 

- becomes: -

+ becomes:

if (foo == 2)
-     a = bar((b - c) * a, d--);
+    a = bar((b - c) * a, d--);
 

-   -

+  

+

+ --pad-comma / -xg
+ Insert space padding after commas. This is not needed if pad-oper is used. 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.

+
+
if (isFoo(a,b)
+    bar(a,b);
+
+

+ becomes:

+
if (isFoo(a, b)
+    bar(a, b);
+
+
+

+  

--pad-paren / -P
Insert space padding around parenthesis on both the outside and the inside. - Any end of line comments will remain in the original column, if possible. -

+ Any end of line comments will remain in the original column, if possible.

if (isFoo((a+2), b))
     bar(a, b);
 

- becomes: -

+ becomes:

if ( isFoo ( ( a+2 ), b ) )
     bar ( a, b );
 

-   -

+  

--pad-paren-out / -d
Insert space padding around parenthesis on the outside only. Parentheses that are empty will not be padded. Any end of line comments will remain in the original column, if possible. This can be used with - unpad-paren below to remove unwanted spaces. -

+ unpad-paren below to remove unwanted spaces.

if (isFoo((a+2), b))
     bar(a, b);
 

- becomes: -

+ becomes:

if (isFoo ( (a+2), b) )
     bar (a, b);
 

-   -

+  

--pad-first-paren-out / -xd
@@ -1581,108 +1419,94 @@ isBar = false; only. Parentheses that are empty will not be padded. Any end of line comments will remain in the original column, if possible. This can be used with unpad-paren below to remove unwanted spaces. If used with pad‑paren or pad‑paren‑out, this option will be ignored. If used with pad‑paren‑in, the result will - be the same as pad‑paren. -

+ be the same as pad‑paren.

if (isFoo((a+2), b))
     bar(a, b);
 

- becomes: -

+ becomes:

if (isFoo ((a+2), b))
     bar (a, b);
 

-   -

+  

--pad-paren-in / -D
Insert space padding around parenthesis on the inside only. Any end of line comments will remain - in the original column, if possible. This can be used with unpad-paren below to remove unwanted spaces. -

+ in the original column, if possible. This can be used with unpad-paren below to remove unwanted spaces.

if (isFoo((a+2), b))
     bar(a, b);
 

- becomes: -

+ becomes:

if ( isFoo( ( a+2 ), b ) )
     bar( a, b );
 

-   -

+  

--pad-header / -H
Insert space padding between a header (e.g. 'if', 'for', 'while'...) and the following paren. Any end of line comments will remain in the original column, if possible. This can - be used with unpad-paren to remove unwanted spaces. -

+ be used with unpad-paren to remove unwanted spaces.

if(isFoo((a+2), b))
     bar(a, b);

- becomes: -

+ becomes:

if (isFoo((a+2), b))
     bar(a, b);
 

-   -

+  

--unpad-paren / -U
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 pad‑paren, pad‑paren‑out, pad‑paren‑in, and pad‑header - above. Only padding that has not been requested by other options will be removed. -

+ above. Only padding that has not been requested by other options will be removed.

For example, if a source has parens padded on both the inside and outside, and you want inside only. You need - to use unpad-paren to remove the outside padding, and pad‑paren‑in to retain - the inside padding. Using only pad‑paren‑in would not remove the outside padding. -

+ to use unpad-paren to remove the outside padding, and pad‑paren‑in to + retain the inside padding. Using only pad‑paren‑in would not remove the outside + padding.

if ( isFoo( ( a+2 ), b ) )
     bar ( a, b );
 

- becomes (with no padding option requested): -

+ becomes (with no padding option requested):

if(isFoo((a+2), b))
     bar(a, b);
 

-   -

+  

--delete-empty-lines / -xe
Delete empty lines within a function or method. Empty lines outside of functions or methods are NOT deleted. If used with break-blocks or break-blocks=all it will delete all lines EXCEPT the lines added by the break-blocks - options. -

+ options.

void Foo()
 {
-	
+
     foo1 = 1;
-	
+
     foo2 = 2;
-	
+
 }
 

- becomes: -

+ becomes:

void Foo()
 {
     foo1 = 1;
@@ -1691,33 +1515,27 @@ isBar = false;
 

-   -

+  

--fill-empty-lines / -E
- Fill empty lines with the white space of the previous line. -

+ Fill empty lines with the white space of the previous line.

-   -

+  

- - --align-pointer=type   / -k1
+ --align-pointer=type   / -k1
--align-pointer=middle / -k2
--align-pointer=name   / -k3

Attach a pointer or reference operator (*, &, or ^) to either the variable type (left) or variable name (right), or place it between the type and name (middle). The spacing between the type and name will be preserved, if possible. This option is for C/C++, C++/CLI, and C# files. To format references separately use the following align-reference - option. -

+ option.

char* foo1;
 char & foo2;
 String ^s1;

- becomes (with align-pointer=type): -

+ becomes (with align-pointer=type):

char* foo1;
 char& foo2;
 String^ s1;
@@ -1727,8 +1545,7 @@ String^ s1;
char & foo2; String ^s1;

- becomes (with align-pointer=middle): -

+ becomes (with align-pointer=middle):

char * foo1;
 char & foo2;
 String ^ s1;
@@ -1738,18 +1555,15 @@ String ^ s1; char & foo2; String ^s1;

- becomes (with align-pointer=name): -

+ becomes (with align-pointer=name):

char *foo1;
 char &foo2;
 String ^s1;

-   -

+  

- - --align-reference=none   / -W0
+ --align-reference=none   / -W0
--align-reference=type   / -W1
--align-reference=middle / -W2
--align-reference=name   / -W3 @@ -1757,32 +1571,27 @@ String ^s1; This option will align references separate from pointers. Pointers are not changed by this option. If pointers and references are to be aligned the same, use the previous align-pointer option. The option align-reference=none will not change the reference alignment. The other options are the same as for align-pointer. This option is for - C/C++, C++/CLI, and C# files. -

+ C/C++, C++/CLI, and C# files.

char &foo1;

- becomes (with align-reference=type): -

+ becomes (with align-reference=type):

char& foo1;
char& foo2;

- becomes (with align-reference=middle): -

+ becomes (with align-reference=middle):

char & foo2;
char& foo3;

- becomes (with align-reference=name): -

+ becomes (with align-reference=name):

char &foo3;

-   -

+  


@@ -1794,41 +1603,36 @@ String ^s1;
When used with --style=java, --style=kr, --style=stroustrup, --style=linux, or --style=1tbs, this breaks closing headers (e.g. 'else', 'catch', ...) from their immediately preceding closing brackets. Closing header brackets - are always broken with the other styles. -

+ are always broken with the other styles.

void Foo(bool isFoo) {
     if (isFoo) {
         bar();
-        } else {
+    } else {
         anotherBar();
-        }
+    }
 }
 

- becomes (a broken 'else'): -

+ becomes (a broken 'else'):

void Foo(bool isFoo) {
     if (isFoo) {
         bar();
-        }
+    }
     else {
         anotherBar();
-        }
+    }
 }
 

-   -

+  

--break-elseifs / -e
Break "else if" header combinations into separate lines. This option has no effect if keep-one-line-statements - is used, the "else if" statements will remain as they are. -

+ is used, the "else if" statements will remain as they are.

- If this option is NOT used, "else if" header combinations will be placed on a single line. -

+ If this option is NOT used, "else if" header combinations will be placed on a single line.

if (isFoo) {
     bar();
@@ -1841,110 +1645,96 @@ else if (isFoo2()) {
 }
 

- becomes: -

+ becomes:

if (isFoo) {
     bar();
 }
 else
     if (isFoo1()) {
         bar1();
-        }
-  else
+    }
+    else
         if (isFoo2()) {
             bar2();
         }
 

-   -

+  

--add-brackets / -j
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 --add-one-line-brackets is also used the result will be one line brackets. -

+ will be attached. If --add-one-line-brackets is also used the result will be one line brackets.

if (isFoo)
     isFoo = false;
 

- becomes: -

+ becomes:

if (isFoo) {
     isFoo = false;
 }
 

-   -

+  

--add-one-line-brackets / -J
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 --keep-one-line-blocks and - will not break the one line blocks. -

+ will not break the one line blocks.

if (isFoo)
     isFoo = false;
 

- becomes: -

+ becomes:

if (isFoo)
-        { isFoo = false; }
+    { isFoo = false; }
 

-   -

+  

--remove-brackets / -xj
Remove brackets from conditional statements (e.g. 'if', 'for', 'while'...). The statement must be a single statement on a single line. If --add-brackets or --add-one-line-brackets is also - used the result will be to add brackets. Brackets will not be removed from "One True Brace Style", --style=1tbs. -

+ used the result will be to add brackets. Brackets will not be removed from "One True Brace Style", + --style=1tbs.

if (isFoo)
 {
     isFoo = false;
 }

- becomes: -

+ becomes:

if (isFoo)
     isFoo = false;
 

-   -

+  

--keep-one-line-blocks / -O
- Don't break one-line blocks. -

+ Don't break one-line blocks.

if (isFoo)
 { isFoo = false; cout << isFoo << endl; }
 

- remains unchanged. -

+ remains unchanged.

-   -

+  

--keep-one-line-statements / -o
- Don't break complex statements and multiple statements residing on a single line. -

+ Don't break complex statements and multiple statements residing on a single line.

if (isFoo)
 {
@@ -1952,217 +1742,210 @@ else
 }
 

- remains unchanged. -

+ remains unchanged.

if (isFoo) DoBar();
 

- remains unchanged. -

+ remains unchanged.

-   -

+  

--convert-tabs / -c
Converts tabs into 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 if convert-tabs is used when changing spaces per tab. Tabs are - not replaced in quotes. -

+ not replaced in quotes.

-   -

+  

--close-templates / -xy
Closes whitespace in the angle brackets of template definitions. Closing the ending angle brackets is now allowed - by the C++11 standard. Be sure your compiler supports this before making the changes. -

+ by the C++11 standard. Be sure your compiler supports this before making the changes.

Stack< int,List< int > > stack1;

- becomes: -

+ becomes:

Stack<int,List<int>> stack1;

-   -

+  

--remove-comment-prefix / -xp
Remove the preceding '*' in a multi-line comment that begins a line. A trailing '*', if present, is also removed. Text that is less than one indent is indented to one indent. Text greater than one indent is not changed. Multi-line comments that begin a line but without the preceding '*' are indented to one indent for consistency. This can slightly modify the indentation of commented out blocks of code. Lines containing all '*' are left unchanged. - Extra spacing is removed from the comment close '*/'. -

+ Extra spacing is removed from the comment close '*/'.

/*
  * comment line 1
  * comment line 2
  */

- becomes: -

+ becomes:

/*
     comment line 1
     comment line 2
 */

-   -

+  

- - --max-code-length=#   / -xC# + --max-code-length=#   / -xC#
- --break-after-logical / -xL -

+ --break-after-logical / -xL

The option max‑code‑length will break a line if the code exceeds # characters. The valid values are 50 thru 200. Lines without logical conditionals will break on a logical conditional - (||, &&, ...), comma, paren, semicolon, or space. -

+ (||, &&, ...), comma, paren, semicolon, or space.

Some code will not be broken, such as comments, quotes, and arrays. If used with keep‑one‑line‑blocks or add-one-line-brackets the blocks will NOT be broken. If used with keep‑one‑line‑statements the statements will be broken at a semicolon if the line goes over the maximum length. If there is no available break point within the max code length, the line will be broken at the first available break point after the max - code length. -

+ code length.

By default logical conditionals will be placed first on the new line. The option break‑after‑logical will cause the logical conditionals to be placed last on the previous line. This option has no effect without - max‑code‑length. -

+ max‑code‑length.

if (thisVariable1 == thatVariable1 || thisVariable2 == thatVariable2 || thisVariable3 == thatVariable3)
     bar();

- becomes: -

+ becomes:

if (thisVariable1 == thatVariable1
         || thisVariable2 == thatVariable2
         || thisVariable3 == thatVariable3)
     bar();

- becomes (with break‑after‑logical): -

+ becomes (with break‑after‑logical):

if (thisVariable1 == thatVariable1 ||
         thisVariable2 == thatVariable2 ||
         thisVariable3 == thatVariable3)
     bar();

-   -

+  

--mode=c
--mode=cs
--mode=java
- Indent a C type, C#, or Java file. C type files are C, C++, C++/CLI, and Objective-C.  The option is usually + Indent a C type, C#, or Java file. C type files are C, C++, C++/CLI, and Objective-C. The option is usually set from the file extension for each file. You can override the setting with this entry. It will be used for all files regardless of the file extension. It allows the formatter to identify language specific syntax such as C++ - classes, templates, and keywords. -

+ classes, templates, and keywords.

-   -

+  


Objective‑C Options

+

+ These options are effective for Objective‑C files only. The paren padding options will still apply to the + Objective-C method prefix and return type unless overridden by the following options.

Because of the longer indents sometimes needed for Objective‑C, the option "max-instatement-indent" may - need to be increased. If you are not getting the paren and square bracket alignment you want, try increasing this - value. The option is described in the "Indentation Options" section. -

+ need to be increased. If you are not getting the paren and square bracket alignment you want try increasing this + value. The option is described in the "Indentation Options" section.

+

+ --pad-method-prefix / -xQ
+ Insert space padding after the '-' or '+' Objective‑C method prefix. This will add + exactly one space. Any additional spaces will be deleted. This option takes precedence over the pad-paren + options.

+
+
-(void)foo1;
++(void)foo2;
+

+ becomes:

+
- (void)foo1;
++ (void)foo2;
+
+

+  

+

+ --unpad-method-prefix / -xR
+ Remove all space padding after the '-' or '+' Objective‑C method prefix.  + This option will be ignored if used with pad‑method‑prefix. It takes precedence over the pad-paren + options.

+
+
- (void)foo1;
++ (void)foo2;
+

+ becomes:

+
-(void)foo1;
++(void)foo2;
+
+

+  

+

+ --pad-return-type / -xq
+ Insert space padding after the Objective‑C return type. This will add exactly one + space. Any additional spaces will be deleted. This option takes precedence over the pad-paren options.

+
+
-(void)foo1;
++(void)foo2;
+

+ becomes:

+
-(void) foo1;
++(void) foo2;
+
+

+  

+

+ --unpad-return-type / -xr
+ Remove all space padding after the Objective‑C return type. This option + will be ignored if used with pad‑return‑type. It takes precedence over the pad-paren options.

+
+
-(void) foo1;
++(void) foo2;
+

+ becomes:

+
-(void)foo1;
++(void)foo2;
+
+

+  

--align-method-colon / -xM
- Align the colons in Objective‑C method declarations. This option is effective for Objective‑C - files only. -

+ Align the colons in Objective‑C method declarations.

-(void)deleteKey:(id)key
     atIndex:(int)index
     ofNode:(Node*)node;

- becomes: -

+ becomes:

-(void)deleteKey:(id)key
          atIndex:(int)index
           ofNode:(Node*)node;

-   -

-

- --pad-method-prefix / -xQ
- Insert space padding after the '-' or '+' Objective‑C method prefix. This will add exactly one space. Any - additional spaces will be deleted. This option is effective for Objective‑C files only. -

-
-
-(void)foo1;
-+(void)foo2;
-

- becomes: -

-
- (void)foo1;
-+ (void)foo2;
-
-

-   -

-

- --unpad-method-prefix / -xR
- Remove all space padding after the '-' or '+' Objective‑C method prefix. If used with pad‑method‑prefix, - this option will be ignored. This option is effective for Objective‑C files only. -

-
-
- (void)foo1;
-+ (void)foo2;
-

- becomes: -

-
-(void)foo1;
-+(void)foo2;
-
-

-   -

+  

- - --pad-method-colon=none   / -xP0
+ --pad-method-colon=none   / -xP0
--pad-method-colon=all    / -xP1
--pad-method-colon=after  / -xP2
--pad-method-colon=before / -xP3

Add or remove space padding before or after the colons in an Objective‑C method call. These options will - pad exactly one space. Any additional spaces will be deleted. Colons immediately preceding a paren will not be - padded. This option is effective for Objective‑C files only. -

+ pad exactly one space. Any additional spaces will be deleted.

- with pad-method-colon=none: -

+ with pad-method-colon=none:

[node insertKey:key];

- with pad-method-colon=all: -

+ with pad-method-colon=all:

[node insertKey : key];

- with pad-method-colon=after: -

+ with pad-method-colon=after:

[node insertKey: key];

- with pad-method-colon=before: -

+ with pad-method-colon=before:

[node insertKey :key];

-   -

+  


@@ -2170,103 +1953,86 @@ else

Other Options

- These are non-formatting options available for the command-line. They can also be included in an options file. -

+ These are non-formatting options available for the command-line. They can also be included in an options + file.

--suffix=####
Append the suffix #### instead of '.orig' to original file name (e.g. --suffix=.bak). If this is to be a file extension, the dot '.' must be included. Otherwise the suffix will be appended to the - current file extension. -

+ current file extension.

--suffix=none / -n
- Do not retain a backup of the original file. The original file is purged after it is formatted. -

+ Do not retain a backup of the original file. The original file is purged after it is formatted.

--recursive / -r / -R
For each directory in the command line, process all subdirectories recursively. When using the recursive option the file name statement should contain a wildcard. Linux users should place the file path and name in double quotes so the shell will not resolve the wildcards (e.g. "$HOME/src/*.cpp"). Windows users should place the file path - and name in double quotes if the path or name contains spaces. -

+ and name in double quotes if the path or name contains spaces.

--dry-run
- Perform a trial run with no changes made to the files. The report will be output as usual. -

+ Perform a trial run with no changes made to the files. The report will be output as usual.

--exclude=####
- Specify a file or sub directory #### to be excluded from processing.  -

+ Specify a file or sub directory #### to be excluded from processing.

Excludes are matched from the end of the file path. An exclude option of "templates" will exclude ALL directories named "templates". An exclude option of "cpp/templates" will exclude ALL "cpp/templates" directories. You may - proceed backwards in the directory tree to exclude only the required directories. -

+ proceed backwards in the directory tree to exclude only the required directories.

- Specific files may be excluded in the same manner. An exclude option of "default.cpp" will exclude ALL files named - "default.cpp". An exclude option of "python/default.cpp" will exclude ALL files named "default.cpp" contained - in a "python" subdirectory. You may proceed backwards in the directory tree to exclude only the required files. -

+ Specific files may be excluded in the same manner. An exclude option of "default.cpp" will exclude ALL files + named "default.cpp". An exclude option of "python/default.cpp" will exclude ALL files named "default.cpp" + contained in a "python" subdirectory. You may proceed backwards in the directory tree to exclude only the + required files.

Wildcards are NOT allowed. There may be more than one exclude statement. The file path and name may be placed - in double quotes (e.g. ‑‑exclude="foo bar.cpp"). -

+ in double quotes (e.g. ‑‑exclude="foo bar.cpp").

--ignore-exclude-errors / -i
Allow processing to continue if there are errors in the "exclude=###" options.
This option lets the excludes for several projects be entered in a single option file. This option may be placed in the same option file as the excludes. It will display the unmatched excludes. The following option will not - display the unmatched excludes. -

+ display the unmatched excludes.

--ignore-exclude-errors-x / -xi
Allow processing to continue if there are errors in the "exclude=###" options.
This option lets the excludes for several projects be entered in a single option file. This option may be placed in the same option file as the excludes. It will NOT display the unmatched excludes. The preceding option will - display the unmatched excludes.
-

+ display the unmatched excludes.

--errors-to-stdout / -X
Print errors to standard-output rather than to standard-error.
This option should be helpful for systems/shells that do not have a separate output to standard-error, such as - in Windows95. -

+ in Windows95.

--preserve-date / -Z
Preserve the original file's date and time modified. The time modified will be changed a few micro seconds to - force the changed files to compile. This option is not effective if redirection is used to rename the input file. -

+ force the changed files to compile. This option is not effective if redirection is used to rename the input + file.

--verbose / -v
- Verbose display mode. Display optional information, such as release number and statistical data. -

+ Verbose display mode. Display optional information, such as release number, date, and statistical data.

--formatted / -Q
Formatted files display mode. Display only the files that have been formatted. Do not display files that - are unchanged. -

+ are unchanged.

--quiet / -q
- Quiet display mode. Suppress all output except error messages. -

+ Quiet display mode. Suppress all output except error messages.

- - --lineend=windows / -z1
+ --lineend=windows / -z1
--lineend=linux   / -z2
--lineend=macold  / -z3

Force use of the specified line end style. Valid options are windows (CRLF), linux (LF), and macold (CR). MacOld style is the format for Mac OS 9 and earlier. OS X uses the Linux style. If one of these options - is not used the line ends will be determined automatically from the input file. -

+ is not used the line ends will be determined automatically from the input file.

When redirection is used on Windows the output will always have Windows line ends. This option - will be ignored. -

+ will be ignored.

-   -

+  


@@ -2277,108 +2043,54 @@ else

--options=####
Specify an options file #### to read and use. It must contain a file path for the file. This will allow the file - name to be changed from astylerc or .astylerc. -

+ name to be changed from astylerc or .astylerc.

--options=none
- Disable the default options file. Only the command-line parameters will be used. -

+ Disable the default options file. Only the command-line parameters will be used.

--ascii / -I
The displayed output will be ascii characters only. The text will be displayed in English and numbers will not - be formatted. The short option must be by itself, it cannot be concatenated with other options. -

+ be formatted. The short option must be by itself, it cannot be concatenated with other options.

--version / -V
- Print version number and quit. The short option must be by itself, it cannot be concatenated with other options. -

+ Print version number and quit. The short option must be by itself, it cannot be concatenated with other + options.

--help / -h / -?
- Print a help message and quit. The short option must be by itself, it cannot be concatenated with other options. -

+ Print a help message and quit. The short option must be by itself, it cannot be concatenated with other + options.

--html / -!
Open the HTML help file "astyle.html" in the default browser and quit. The short option must be by itself, it cannot be concatenated with other options. The documentation must be installed in the standard install path (/usr/share/doc/astyle/html - for Linux or %PROGRAMFILES%\AStyle\doc for Windows). If installed to a different path use html=###. -

+ for Linux or %PROGRAMFILES%\AStyle\doc for Windows). If installed to a different path use html=###.

--html=####
Open a HTML help file in the default browser using the file path #### and quit. A HTML file other than "astyle.help" may be specified. The path may include a directory path and a file name, or a file name only (e.g. html=install.html). If only a file name is used it is assumed to be in the standard install path (/usr/share/doc/astyle/html for Linux or %PROGRAMFILES%\AStyle\doc for Windows). In both cases the file name must include the html extension. - File paths containing spaces must be enclosed in quotes. -

+ File paths containing spaces must be enclosed in quotes.

On Linux the HTML file is opened using the script "xdg-open" from the install package "xdg-utils". This should - be installed - by default on most distributions. -

+ be installed by default on most distributions.

Any HTML file can be opened by this option. The files you are likely to need are astyle.html (the default), install.html, - and index.html. -

+ and index.html.

-   -

+  


- +

+ + +

-   -

+  

-   -

- - - - - - - - - - +  

diff --git a/doc/favicon.ico b/doc/favicon.ico new file mode 100644 index 0000000..0de820b Binary files /dev/null and b/doc/favicon.ico differ diff --git a/doc/install.html b/doc/install.html index a34feff..70c397e 100644 --- a/doc/install.html +++ b/doc/install.html @@ -1,6 +1,6 @@ - + - + Artistic Style - Install Information @@ -12,401 +12,335 @@ -

Artistic Style Install Information -

+

Artistic Style Install Information

-   -

+  

-

- Contents -

+

Contents

- Artistic Style Versions -

+ Artistic Style Versions

- Linux Version -

+ Linux Version

- GCC Compiler -

+ GCC Compiler

- Other Makefile Options -

+ Clang Compiler

- Clang Compiler -

+ Intel Compiler

- Intel Compiler -

+ Other Makefile Targets

- Mac OS X Version -

+ Mac OS Version

- Xcode -

+ Xcode

- Makefile -

+ Makefile

- Windows Version -

+ Windows Version

- Precompiled Executable -

+ Precompiled Executable

- Visual C++ Compiler -

+ Visual C++ Compiler

- Other Compilers -

+ Other Compilers

- Compiler Options -

+ Compiler Options

-

- Artistic Style Versions -

+

Artistic Style Versions

- astyle_x.x_linux.tar.gz is the Linux version of Artistic Style. It contains the source code, documentation, - and makefiles. The Linux Version compile instructions below give information for compiling the source code. -

+ astyle_x.x_linux.tar.gz is the Linux version of Artistic Style. It contains the source code, + documentation, and makefiles. The Linux Version compile instructions below give information for compiling the + source code.

- astyle_x.x_macosx.tar.gz is the Mac OS X version of Artistic Style. It contains the source code, documentation, - Xcode project files, and a makefile. The Mac OS X Version compile instructions below give information for compiling - the source code. -

+ astyle_x.x_macos.tar.gz is the Mac OS version of Artistic Style. It contains the source code, + documentation, Xcode project files, and a makefile. The Mac OS Version compile instructions below give information + for compiling the source code.

- astyle_x.x_windows.zip is the Windows version of Artistic Style. It contains the source code, documentation, - Visual C project files, and an executable. The Windows Version compile instructions below give information for - compiling the source code. -

+ astyle_x.x_windows.zip is the Windows version of Artistic Style. It contains the source code, + documentation, Visual C project files, and an executable. The Windows Version compile instructions below give + information for compiling the source code.

Only one platform is supported in each distribution package. If you use Artistic Style on more than one platform you will need to download packages for each platform. The main difference in platforms is the build directories and the line endings. Most compilers and development packages will accept any type of line ending. The source - code and documentation are the same for all distributions. -

+ code and documentation are the same for all distributions.

-

- Linux Version -

+

Linux Version

-

- GCC Compiler -

+

GCC Compiler

- To compile using the GCC compiler you must have GCC (3.1 or better) installed. -

+ To compile using the GCC compiler you must have GCC (3.1 or better) installed.

The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the astyle/build/gcc directory. The executables will be in the astyle/build/gcc/bin directory. To build the command - line configuration enter the following: -

+ line configuration enter the following:

cd astyle/build/gcc
make

To build the other astyle configurations you can enter the file name or a symbolic name. Entering "make astyle" or "make release" will build the command line configuration. Following are the symbolic names and file names (in - parens) of the various configurations: -

+ parens) of the various configurations:

    -
  • release builds the Artistic Style command line program (astyle). This is the default option.
  • -
  • shared builds the Artistic Style program as a shared library (libastyle.so).
  • -
  • static builds the Artistic Style program as a static library (libastyle.a).
  • -
  • debug builds the Artistic Style command line program with debugging information (astyled).
  • -
  • shareddebug builds the Artistic Style program as a shared library with debugging information (libastyled.so). +
  • release builds the Artistic Style command line program (astyle). This is the default option.
  • -
  • staticdebug builds the Artistic Style program as a static library with debugging information (libastyled.a). +
  • shared builds the Artistic Style program as a shared library (libastyle.so).
  • +
  • static builds the Artistic Style program as a static library (libastyle.a).
  • +
  • debug builds the Artistic Style command line program with debugging information (astyled).
  • -
  • all builds all the above configurations. +
  • shareddebug builds the Artistic Style program as a shared library with debugging information + (libastyled.so). +
  • +
  • staticdebug builds the Artistic Style program as a static library with debugging information + (libastyled.a). +
  • +
  • all builds all the above configurations.

    The following Java shared library builds are separate from the above. They include a Java Native Interface (JNI) and require that the Java Development Kit (JDK) be installed. The environment variable JAVA_HOME should be defined. It defines the install directory for the JDK. The makefile also has default install directories for Java 5 and - 6. If the compile cannot find the file jni.h, either set the variable or change the value in the makefile. -

    + 6. If the compile cannot find the file jni.h, either set the variable or change the value in the + makefile.

  • -
  • java builds the Artistic Style program as a shared library which includes the JNI (libastylej.so).
  • -
  • javadebug builds the Artistic Style program as a shared library which includes the JNI and debugging information +
  • java builds the Artistic Style program as a shared library which includes the JNI (libastylej.so). +
  • +
  • javadebug builds the Artistic Style program as a shared library which includes the JNI and debugging + information (libastylejd.so).
  • javaall builds all the above java configurations.

More than one configuration can be built at the same time. For example, to build all the release configurations - enter: -

+ enter:

cd astyle/build/gcc
make release shared static
+

+ The Other Makefile Targets section contains additional target + options.

-

- Other Makefile Options -

+

Clang Compiler

-

- The following makefile options are available for GCC, Clang, Intel, and Mac. -

-
clean -
-

- Removes the object and executable files for all configurations. -

-

- To remove the files for all configurations: -

-
make clean
-
-
cleanobj -
-

- Removes the object files for all configurations. The executables will not be removed. -

-

- To remove only the object files for all configurations: -

-
make cleanobj
-
-
install -
-

- Installs the - astyle executable and documentation files. The default is /usr/bin for the executable and /usr/share/doc/astyle - for the documentation. You must have the appropriate permissions to use install. -

-

- To install the astyle to the default directories: -

-
sudo make install
-
-

- To install astyle to a different bin directory set a value for the macro $(prefix). For example to install the - executable to a user's home directory (/home/user/bin): -

-
sudo make prefix=$HOME install
-
-
uninstall -
-

- Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall. -

-

- To uninstall astyle from the default directories: -

-
sudo make uninstall
-
-

- To uninstall the files from a different directory set a value for the macro $(prefix). For example to uninstall - the files from a user's home directory (/home/user): -

-
 sudo make prefix=$HOME uninstall
-
-

- NOTE: The uninstall option will NOT remove the .astylerc files from the users home directories. The files must - be removed individually for each user. -

- -

- Clang Compiler -

- -

- The Clang Compiler release 2.9.11 has a problem finding object files on - some distributions (Ubuntu based). There is a script file, copyfiles.sh, that will copy three object files to - the clang build directory so they can be linked. The directory may need to be modified for your distribution. - Or, you may not need it at all. This problem has been fixed in version 3.0. -

Clang has a static analyzer that finds potential bugs in C/C++ and Objective-C programs. It can be run as a standalone tool from the command-line, and runs in tandem with a build. There is a script file, analyze.sh, that will run - the analysis on Artistic Style. -

+ the analysis on Artistic Style.

The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the astyle/build/clang directory. The executables will be in the astyle/build/clang/bin directory. To build the command - line configuration enter the following: -

+ line configuration enter the following:

cd astyle/build/clang
make

To build the other astyle configurations you can enter the file name or a symbolic name. The configurations for Clang are the same as for the GCC compiler. More than one configuration can be - built at the same time. For example, to build all the release configurations enter: -

+ built at the same time. For example, to build all the release configurations enter:

cd astyle/build/clang
make release shared static

- The Other Makefile Options are the same as for the GCC compiler. -

+ The Other Makefile Targets section contains additional target + options.

-

- Intel Compiler -

+

Intel Compiler

These procedures and the makefile are for recent versions of the compiler. They may not work for earlier versions. - Instructions for your compiler are in the compiler documentation file "get_started_lc.htm". -

+ Instructions for your compiler are in the compiler documentation file "get_started_lc.htm".

To compile the source there are environment variables that must be set by running the compiler environment script compilervars.sh (or compilervars.csh) with an argument that specifies the target architecture. If this has not been done already enter: "source  <install-dir>/bin/compilervars.sh <arg>", where <install-dir> is the directory where the compiler is installed and <arg> is ia32 or intel64. If this is not done "make" will display an error message "*** The compiler environment - variables are not set." On an Intel x64 platform installed in the default directory the instruction would be -

+ variables are not set." On an Intel x64 platform installed in the default directory the instruction would + be

source /opt/intel/bin/compilervars.sh intel64

The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the astyle/build/intel directory. The output executables will be in the astyle/build/intel/bin directory. To build - the command line configuration enter the following: -

+ the command line configuration enter the following:

cd astyle/build/intel
make

To build the other astyle configurations you can enter the file name or a symbolic name. The configuration names for Intel are the same as for the GCC compiler. More than one configuration can be - built at the same time. For example, to build the entire debug configurations enter: -

+ built at the same time. For example, to build the entire debug configurations enter:

cd astyle/build/intel
make debug shareddebug staticdebug

- The Other Makefile Options are the same as for the GCC compiler. -

+ The Other Makefile Targets section contains additional target + options.

-

- Mac OS X Version -

+

Other Makefile Targets

+ +

+ The following makefile targets are available for GCC, Clang, Intel, and Mac.

+ +
clean
+ +

+ Removes the object and executable files for all configurations.

+

+ To remove the files for all configurations:

+
make clean
+
+ +
cleanobj
+ +

+ Removes the object files for all configurations. The executables will not be removed.

+

+ To remove only the object files for all configurations:

+
make cleanobj
+
+ +
install
+ +

+ Installs the + astyle executable and documentation files. The default is /usr/bin for the executable and /usr/share/doc/astyle + for the documentation. You must have the appropriate permissions to use install.

+

+ To install the astyle to the default directories:

+
sudo make install
+
+

+ To install astyle to a different bin directory set a value for the macro $(prefix). For example to install the + executable to a user's home directory (/home/user/bin):

+
sudo make prefix=$HOME install
+
+ +
uninstall
+ +

+ Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall.

+

+ To uninstall astyle from the default directories:

+
sudo make uninstall
+
+

+ To uninstall the files from a different directory set a value for the macro $(prefix). For example to uninstall + the files from a user's home directory (/home/user):

+
 sudo make prefix=$HOME uninstall
+
+

+ NOTE: The uninstall option will NOT remove the .astylerc files from the users home directories. The files must + be removed individually for each user.

+ +

Mac OS Version

Xcode

Artistic Style workspace and project files for the Xcode development environment are available in the "build/xcode" directory. A workspace can be used to build a single project or all the projects. The project files have Debug - and Release configurations. The following projects are available. -

+ and Release configurations. The following projects are available.

    -
  • AStyle builds the Artistic Style command line program (astyle).
  • -
  • AStyleA builds the Artistic Style program as a Static Library (libastyle.a). This can be statically +
  • AStyle builds the Artistic Style command line program (astyle).
  • +
  • AStyleA builds the Artistic Style program as a Static Library (libastyle.a). This can be statically linked with an executable.
  • -
  • AStyleDylib builds the Artistic Style program as a Dynamic Library (libastyle.dylib). It can be used with C/C++, Objective - C, C#, and Python programs.
  • -
  • AStyleJava builds the Artistic Style program as a Dynamic Library (libastylej.dylib) that can be called - from a Java program. The Java Development (JDK) is required for the project to compile. The Project Properties - must have an include path to the JDK include directory. The output dylib can also be called from a C++ or C# - program.
  • +
  • AStyleDylib builds the Artistic Style program as a Dynamic Library (libastyle.dylib). It can + be used with C/C++, Objective C, C#, and Python programs.
  • +
  • AStyleJava builds the Artistic Style program as a Dynamic Library (libastylej.dylib) that can + be called from a Java program. The Java Development (JDK) is required for the project to compile. The Project + Properties must have an include path to the JDK include directory. The output dylib can also be called from a + C++ or C# program.
install
+

Only the astyle executable is installed. The library project installs are sent to UninstalledProjects in the Build directory. The following instructions are for the astyle executable and documentation files. The default install directory is /usr/bin for the executable and /usr/share/doc/astyle for the documentation. You must have the appropriate permissions to use install. - If sudo is not used for the install an error will occur during the build. -

+ If sudo is not used for the install an error will occur during the build.

- To install the astyle executable to the default directory: -

+ To install the astyle executable to the default directory:

cd astyle/build/xcode
 sudo xcodebuild install -project AStyle.xcodeproj
 

A script is used to install the documentation - from the same directory. -

+ from the same directory.

sudo bash install.sh
 
-
uninstall -
+ +
uninstall
+

- Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall. -

+ Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall.

- A script is used to uninstall astyle and the documentation: -

+ A script is used to uninstall astyle and the documentation:

sudo bash uninstall.sh
 

NOTE: The uninstall option will NOT remove the .astylerc files from the users home directories. The files must - be removed individually for each user. -

+ be removed individually for each user.

Makefile

- The Artistic Style makefile compile uses the OS X "Command Line Tools". If you have Xcode 4.3 or newer + The Artistic Style makefile compile uses the Mac OS "Command Line Tools". If you have Xcode 4.3 or newer the command line tools, such as "make", are NOT installed by default. They must be downloaded and installed separately. Once everything is successfully installed you should see "make" and other command line developer - tools in /usr/bin. -

+ tools in /usr/bin.

The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the astyle/build/mac directory. The executables will be in the astyle/build/mac/bin directory. To build the command - line configuration enter the following: -

+ line configuration enter the following:

cd astyle/build/mac
make

To build the other astyle configurations you can enter the file name or a symbolic name. The configurations for Mac are the same as for the Linux GCC compiler. More than one configuration can be - built at the same time. For example, to build all the release configurations enter: -

+ built at the same time. For example, to build all the release configurations enter:

cd astyle/build/mac
make release shared static

- The Other Makefile Options are the same as for the Linux GCC compiler. -

+ The Other Makefile Targets section contains additional target + options.

-

- Windows Version -

+

Windows Version

-

- Precompiled Executable -

+

Precompiled Executable

In addition to the source files, the Windows distribution package contains an Artistic Style Win32 executable - (AStyle.exe). If you prefer to compile the executable yourself follow the following instructions. -

+ (AStyle.exe). If you prefer to compile the executable yourself follow the following instructions.

-

- Visual C++ Compiler -

+

Visual C++ Compiler

- There are configuration and project files for - several versions of the Visual C compiler. Open the AStyle configuration - file in the appropriate "build" directory. All project files have Debug, Release and Static configurations. + There are + solution and project files for + several versions of the Visual C compiler. Open an Artistic Style solution + file in the appropriate "build" directory. All projects have Debug, Release and Static configurations. Debug file output will be in the "debug" directory. Release file output will be in the "bin" - directory. Static file output will be in the "binstatic" directory. The following solution files are available. -

+ directory. Static file output will be in the "binstatic" directory. The following solution files are + available.

    -
  • All AStyle builds the release and the debug configurations for all the following.
  • -
  • AStyle builds the Artistic Style command line program (AStyle.exe). This project has an extra "Static" - option. It is the same as the "Release" build except that it is linked with a static runtime library. This is - needed if the executable is to be run on a system without Visual Studio installed. The builds for this configuration - are placed in a separate "binstatic" directory.
  • -
  • AStyleDll builds the Artistic Style program as a Dynamic Link Library (AStyle.dll). This will also build - an exports library and a static library for linking the dll.
  • -
  • AStyleJava builds the Artistic Style program as a Dynamic Link Library (AStylej.dll) that can be called - from a Java program. The Java Development (JDK) is required for the project to compile. The Project Properties - must have an include path to the JDK include and include/win32 directories. This is set in "Project > - Properties > C/C++ > General > Additional Include Directories". The default setting is - for the JDK to be installed in the default directory, but it may not be the most current release. The output DLL - can also be called from a C++ or C# program.
  • -
  • AStyleLib builds the Artistic Style program as a Static Library (libAStyle.lib). This can be statically - linked to a calling program.
  • +
  • All AStyle ll AStyle builds the release and the debug configurations for all the following. +
  • +
  • AStyle builds the Artistic Style command line program (AStyle.exe). This project has an extra + "Static" option. It is the same as the "Release" build except that it is linked with a static runtime library. + This is needed if the executable is to be run on a system without Visual Studio installed. The builds for this + configuration are placed in a separate "binstatic" directory.
  • +
  • AStyleDll builds the Artistic Style program as a Dynamic Link Library (AStyle.dll). This will + also build an exports library and a static library for linking the dll.
  • +
  • AStyleJava builds the Artistic Style program as a Dynamic Link Library (AStylej.dll) that can + be called from a Java program. The Java Development (JDK) is required for the project to compile. The Project + Properties must have an include path to the JDK include and include/win32 directories. This is set in "Project + > Properties > C/C++ > General > Additional Include Directories". The default setting + is for the JDK to be installed in the default directory, but it may not be the most current release. The output + DLL can also be called from a C++ or C# program.
  • +
  • AStyleLib builds the Artistic Style program as a Static Library (libAStyle.lib). This can be + statically linked to a calling program.
-

- Other Compilers -

+

Other Compilers

- To use other compilers a project file must be built using a development environment. -

+ To use other compilers a project file must be built using a development environment.

  • Create a project using the compiler's development environment.
  • Add to the project all the .cpp and .h files in the "src" directory.
  • @@ -414,61 +348,32 @@ sudo xcodebuild install -project AStyle.xcodeproj
  • Compile.
-

- Compiler Options -

+

Compiler Options

No macro definitions are required to compile the executable. To compile as a static or shared (dynamic) library - define the macro ASTYLE_LIB. To compile a Java shared (dynamic) library define the macro ASTYLE_JNI. The - option ASTYLE_NO_EXPORTS is sometimes needed for static libraries to prevent compiler error and warning + define the macro ASTYLE_LIB. To compile a Java shared (dynamic) library define the macro ASTYLE_JNI. The + option ASTYLE_NO_EXPORTS is sometimes needed for static libraries to prevent compiler error and warning messages. Use the appropriate compiler and linker options to compile the static or shared library. Add debug - options to compile the debug versions. -

+ options to compile the debug versions.

Artistic Style is a small program and it is best to optimize for speed. The debug configurations are not usually optimized. To optimize for speed in the release configurations use the macro NDEBUG to remove asserts. If necessary, use an option to activate the C++11 standards (--std=c++0x on GCC and MinGW). Use an - option that allows inline function expansion. Runtime Type Information (RTTI) is NOT needed. Exceptions are not + option that allows inline function expansion. Runtime Type Information (RTTI) is NOT needed. Exceptions are + NOT used. Use whole program optimization if your compiler supports it. There may be other options you can use depending - on the compiler. -

+ on the compiler.

-   -

+  

-
+

- -

+

-   -

- - - - - - - - - - +  

diff --git a/doc/news.html b/doc/news.html index 29bfec9..9f7a947 100644 --- a/doc/news.html +++ b/doc/news.html @@ -1,6 +1,6 @@ - + - + Artistic Style - News @@ -15,167 +15,332 @@

Artistic Style News

-   -

+  

+ +

Artistic Style 2.06  (Pending)

+ +

+ A new option, "pad-comma", will add a space following a comma. The option "pad-oper" + has not been changed and will also add a space following a comma.

+

+ All spaces before a comma are now removed. Use the "disable formatting" comment tags if there are arrays + with vertical alignment where this is not wanted.

+

+ New Objective-C options "pad-return-type" and "unpad-return-type" will + add or remove space padding after the Objective-C return type. It is described in the "Objective-C" + section of the documentation.

+

+ The Objective-C align-method-colon has been changed for method declarations and definitions. + For multi-line arguments when the first keyword is shorter than the others the colons are aligned on the + longest line instead of the first line. The alignment includes room for the indentation. This aligns all colons + after the first line for a better appaerance. Arguments that do not have a short keyword in the first line will + remain the same. This style conforms to the Google Objective-C Style Guide.

+

+ The Objective-C align-method-colon option is now applied to Objective-C method calls in + addition to method declarations and definitions.

+

+ Processing for C++14 single-quote digit separators has been added.

+

+ Translations have been added for Bulgarian, Estonian, Greek, Hungarian, Norwegian, and Romanian. The translations + were done with an automated translation program, Google Translate, so they may not be the best translation possible. + The translations are at the end of ASLocalizer.cpp in the form of an English-Translation pair. If you correct + a translation, send the source as a bug report and it will be included in the next release. To add a language, + see "Internationalization" in the "General Information" section of the documentation.

+

+ The C# example in the Developer Information has been updated. Objects for the AStyle callback functions are no + longer required. These have been removed and the delegates used instead.

+

+ There is a new C# example in the Developer Information that loads the AStyle shared library using explicit linking. + This allows the shared library name to be changed so that a program compiled with "Any CPU" can load + either a 32-bit or 64-bit shared library.

+

+  

+ +

Visual Studio 2015 UTF-8 Files

+ +

+ In order to be used on both Linux and Windows, the ASLocalizer.cpp UTF-8 file in Artistic Style does not + contain a Byte Order Mark (BOM).  With Visual Studio 2015 there has been a change in how UTF-8 files + without a BOM are processed. The new procedure is described + here. + It affects only the language translations in the ".exe" file. The shared libraries and static libraries + are not affected. It is necessary only if you are unsin a translation other than English.

+ +

+ In addition to the "auto detect..." option in Tools > Options... > Text Editor > General, an + additional compiler option is required. The option "/source‑charset:utf‑8" must be added + to the project properties at C++ > Command Line, Additional Options. Since the non‑unicode files in Artistic + Style are ASCII, the option can be applied to the entire project instead of just one file. This option has been + added in the files distributed with Artistic Style. There is also a new "/validate‑charset" option, + which gets turned on automatically with the above option. This switch enables the validation of the UTF-8 input + files.

+

+ This compiler option was not available until Update 2 of Visual Studio. If you are using an earlier version of + 2015, a BOM should be added to the file using File > "Advanced Save Options...". Change the encoding + to "Unicode (UTF-8 with signature) - Codepage 65001".

+

+ In the above "Visual C++ Team Blog" Microsoft mentions that in a future major release of the compiler, + they would like to change default handling of BOM-less files to assume UTF-8.

+ +

New Software License

+ +

+ The Artisic Style software license has changed. It is now under the MIT license. This is a permissive license + which can be used in proprietory software and does NOT require modified Artistic Style source code be made available. + It is compatable with the GNU General Public License (GPL) and most other software licenses. The change was made + to remove restrictions on using the software and to make it available for any project that wants to + use it.

+

+ If there are problems with the license change send an email to Artistic Style and its use will be approved on + a individual basis.

+ +

Assignment Operator Alignment

+ +

+ Visual Studio 2013 and 2015 have an Edit option "Align Assignments" that will align assignment operators + across multiple lines. There is also an extension named "Code alignment" that will align the code on + other items as well. Other development environments may have something similar. These will selectively align the + data and allow for customization of the format.

+

+ These options and extensions can be used with Artistic Style. If you choose to do this, the space padding will + be maintained and the alignment will be preserved.

+ +

Microsoft Clang Compiler

+ +

+ The Microsoft Clang Compiler is available starting with Visual Studio 2015 Update 2. It is usually used for Android + or iOS support but the CodeGen support can be used with Windows. It will require modification of the Visual Studio + 2015 project files.

+

+ The Clang compiler can be installed from the Visual Studio 2015 install program by selecting the "Clang + with Microsoft CodeGen" option. If Visual Studio 2015 Update 2 or 3 is already installed, Clang can be installed + by selecting File > New > Project > Visual C++ > Cross Platform, select "Install Clang with Microsoft + CodeGen".

+

+ To use Clang open a Visual Studio 2015 AStyle Solution. Make the following change to all configurations:

+
    +
  • General > Platform Toolset, select "Clang with Microsoft CodeGen".
  • +
+

+ Make sure to hit "Apply" before editing other properties to let the project system load the corresponding + toolset definition.

+

+ The Update 2 and 3 releases do not provide any support for automatic migration of values between Visual Studio + 2015 and Clang. The invalid properties must be fixed manually manually. These properties may change with + subsequent Visual Studio updates.

+

+ The properties that need changing in Visual Studio 2015 Update 2 and 3 are:

+
    +
  • C/C++ > General > Debug Information Format, select "Full Debug Information (DWARF2)" for Debug + or "None" for Release.
  • +
  • C/C++ > General > Warning Level, select "Enable All Warnings".
  • +
  • C/C++ > Optimization > Optimization, select an appropriate valid value for each configuration.
  • +
  • C/C++ > Code Generation > Enable C++ Exceptions, select "Yes" for Debug or "No" for + Release.
  • +
  • C/C++ > Precompiled Headers > Precompiled Header, select "Not Using Precompiled Headers".
  • +
+

+ The following is needed if you are building an executable instead of a static or dynamic library. + The properties must be Clang-compatible options which start with "-"  instead of "/". + The new opton "/source-charset:utf-8" can NOT be used with Clang. If necessary, remove it from C/C++ + > Command Line > Additional Options.

+
    +
  • C/C++ > Preprocessor > Preprocessor Definitions, add " __STDC__=0". +
  • +
  • C/C++ > Command Line > Additional Options, enter "-Wno-macro-redefined". +
  • +
+

+ The project should now compile and run.

+ +

Artistic Style Wx

+ +

+ There is a new GUI test program AStyleWx that uses wxWidgets. This replaces the old AStyleWin program. AStyleWx + is multi-platform. It has more features simply because they are easier to implement with wxWidgets.

+

+ It has download files and a website in a new sub-project directory of Artistic Style. The downloads contain + source code, documentation, and scripts. The Windows download contains an executable. The needed Artistic Style + source files are included.

+

+ It is licensed under the MIT license. The source code may be used and modified for any purpose you + choose. Developers using Artistic Style in another project may use any part of AStyleWx in their project. The + modified source code does NOT need to be made available to others.

+ +

Windows XP

+ +

+ The executable in the Windows distribution package is now compiled with a Visual Studio version that will no + longer work on Windows XP. Beginning with Visual Studio 2012, auto-vectorization tries to make loops run + faster by automatically vectorizing the code. Auto-vectorization is on by default, there are no compiler + switches, #pragmas, or hints. But it uses SSE instructions not available in Windows XP. Microsoft ended + support and updates for XP on April 8, 2014, and the usage share percentage continues to decrease.

+

+ If you are using XP, Artistic Style should be compiled on the XP machine. Compiling on XP with any + compiler should produce an XP executable.

+

+ To compile on a non-XP machine for use on XP, using a compiler other than Visaul Studio should always + produce an XP executable. Using Vusual Studio 2010 or earlier should always produce an XP executable. If + you are using Visual Studio 2012, 2013, or 2015 on a non-XP machine, do the following for the Artistic Style + configuration you want to use:

+
    +
  • "Windows XP Support for C++" must be installed. It is available as an option in the Visual Studio install + and can be installed as a modification to the current install.
  • +
  • In the Artistic Style Properties, change General > Platform Toolset, to "Windows XP" for your Visual + Studio version.
  • +
  • In the Artistic Style Properties, change C/C++ > Preprocessor > Preprocessor Definitions to include + _USING_V110_SDK71_.
  • +
  • Change other Properties if you want, such as Output Directory or Target Name.
  • +
  • Compile. The output should be executable on Windows XP. It will also execute on the later versions of Windows. +
  • +
+

+ In newer releases of Visual Studio 2015, the "Universal CRT" files have been moved. There is a + notification at https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/. + To compile using XP there may need to be additional include and library directories added. If the compile gets + errors add the appropriate directories to the project properties.

+ + +

Acknowledgments

+ +

+ Thanks to David Faure for their contributions.

Artistic Style 2.05  (November 2014)

-

Release 2.05.1 (December 2014) is a maintenance release and no new features were added. A list of changes is in +

+ Release 2.05.1 (December 2014) is a maintenance release and no new features were added. A list of changes is in the Release Notes. The following information is for the original 2.05 release.

A new bracket style option, "style=vtk", has been added. It uses indented brackets, like Whitesmith, except opening brackets for classes, functions, and methods are not indented. A complete description of the VTK - style is available at the "Visualization Toolkit" website (http://www.vtk.org/). -

+ style is available at the "Visualization Toolkit" website (http://www.vtk.org/).

A new preprocessor indent option "indent-preproc-block" will indent preprocessor block statements one additional indent. The block must be top-level, or included within a namespace, and there are restrictions on what can be indented. - The option is described in the "Indentation Options" section of the documentation. -

+ The option is described in the "Indentation Options" section of the documentation.

- A new option, "dry-run", will run Artistic Style without updating the files. The report will be output as usual. -

+ A new option, "dry-run", will run Artistic Style without updating the files. The report will be output as + usual.

Formatting of source code may now be disabled for portions of a program by embedding special comment tags in the program. These are described in a new "Disable Formatting" section of the documentation. They work the same as in other formatters. There are tags to disable formatting for a block of code, and a tag to disable formatting - of a single line. This should allow any custom formatting to be retained. -

+ of a single line. This should allow any custom formatting to be retained.

The product version number has been added to the filename of shared library (DLL) compiles. This will allow multiple - versions of a shared library on the same system without conflicts. -

+ versions of a shared library on the same system without conflicts.

An attribute '__attribute__ ((visibility ("default")))' has been added to exported functions on Linux shared libraries. This allows the option "-fvisibility=hidden" to be used on dynamic library compiles. According to the GNU documentation, "Using this feature can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export and prevent - symbol clashes. It is strongly recommended that you use this in any shared objects you distribute." -

+ symbol clashes. It is strongly recommended that you use this in any shared objects you distribute."

Improvements have been made in the formatting of C++11 uniform initializers (enclosed by brackets). The opening bracket will not be space padded unless it is padded initially. The closing bracket will not be broken from the final line unless it is broken initially. And the known problems with uniform initializers in class constructors - have been fixed. -

+ have been fixed.

The Windows compiler definition ASTYLE_NO_VCX (no Visual Studio exports) has been changed to ASTYLE_NO_EXPORTS. - It is sometimes needed for static libraries on other compilers to prevent error and warning messages. -

+ It is sometimes needed for static libraries on other compilers to prevent error and warning messages.

- Qt and Boost macros foreach, forever, Q_FOREACH, and Q_FOREVER will now be recognized as headers. -

+ Qt and Boost macros foreach, forever, Q_FOREACH, and Q_FOREVER will now be recognized as headers.

The main documentation for Artistic Style is in HTML format. Until now there has not been a way to display it from the astyle console program. A new option, "html" or "-!" will display the help documentation in the default browser. This documentation is more complete than the astyle "help" option. It includes examples, and has an index for easier navigation. Since astyle is typically run from a script this should allow an easy way to access the - documentation. The option is available only from the command line. -

+ documentation. The option is available only from the command line.

The new "html" option assumes the documentation is installed in the standard install path. This is /usr/share/doc/astyle/html for Linux and the path %programfiles%\AStyle\doc for Windows. If it is installed to a different directory, use the variation "html=<actual_install_path>astyle.html. This option can also be used to open other HTML files. - More information is in the "Command Line Only" section of the documentation. -

+ More information is in the "Command Line Only" section of the documentation.

The "html" option on Linux uses the script "xdg-open" from the install package "xdg-utils" to find the default browser. This should be available on most systems.  If it is not available on your system you can file a bug report requesting a change. It would be helpful if you could determine how it is done before filing the report. You can also file a bug report if the documentation is not installed to the above "default" directories. The HTML - documentation takes quite a bit of effort to maintain and I would like to make it easily available. -

+ documentation takes quite a bit of effort to maintain and I would like to make it easily available.

The "help" option has been changed to send the output to stdout instead of stderr. This will allow piping and redirection of the output. A common way to use the option on Linux is "astyle --help | less", which - will page the display. The "version" option has also been changed to stdout. -

+ will page the display. The "version" option has also been changed to stdout.

A shared library error handler argument has been changed from "char*" to "const char*". In - some cases this may cause compile errors in a user program until the references have been changed. -

+ some cases this may cause compile errors in a user program until the references have been changed.

The "Indent Style" topic on Wikipedia states that the "ANSI" style refers to K&R style brackets and not Allman style as used by Artistic Style. The option "style=ansi" is therefore being depreciated and will - be removed in a future release. Use one of the other long options instead (style=allman, style=bsd, or style=break). -

+ be removed in a future release. Use one of the other long options instead (style=allman, style=bsd, or + style=break).

Some of the documentation has been removed from the distribution package. It still contains all files needed to - install and run Artistic Style. The included files can be used without an Internet connection. -

+ install and run Artistic Style. The included files can be used without an Internet connection.

There are now build files available for Xcode on Mac. The makefile is still available for those who want it. Both now use the LLVM Clang compiler. There has been a change to the makefile debug locations to make them similar to Xcode. The "Install Instructions" have - been updated for both. -

+ been updated for both.

- The Python Example in the Developer Information now supports Iron Python. The + The Python Example in the Developer Information now supports Iron Python. The programming instructions are sometimes different since the ctypes module works differently. The example script documents the differences. If you use Python Tools for Visual Studio, it now installs in the Express editions - (beginning with release 2.1). Node.js can also be installed in Visual Studio Express. -

+ (beginning with release 2.1). Node.js can also be installed in Visual Studio Express.

The executable in the Windows distribution package is now compiled with Visual Studio 2013 and will no longer - work on XP. If you are using XP, Artistic Style will need to be recompiled on the XP machine. -

+ work on XP. If you are using XP, Artistic Style will need to be recompiled on the XP machine.

- A new Visual + A new Visual Studio Community Edition has been released. It is free, combines all of the Express editions into a single - development environment, and allows the addition of Visual Studio extensions. There is an - + development environment, and allows the addition of Visual Studio extensions. There is an + AStyle Extension available for installation. It has a graphic interface, adds menu entries, and can be used from within Visual Studio. To install it search the "Extensions and Updates", "Online" - entry for "astyle". -

+ entry for "astyle".

- Thanks to Peter A. Bigot, HyungKi Jeong, David Faure, and Carl Moore for their contributions. -

+ Thanks to Peter A. Bigot, HyungKi Jeong, David Faure, and Carl Moore for their contributions.

Artistic Style 2.04  (November 2013)

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. -

+ Style. You may want to format your source before making program changes in order to bring it up to date.

A new programming language, Objective‑C, has been added to Artistic Style. Four new options, "align‑method‑colon", "pad‑method‑colon=", "pad‑method‑prefix", and "unpad‑method‑prefix" have been added to format the methods. The options are described in a new "Objective‑C" section in the documentation. - These new options affect only Objective‑C source code. They have no effect on the other programming languages. -

+ These new options affect only Objective‑C source code. They have no effect on the other programming + languages.

Because of the longer continuation indents sometimes needed for Objective‑C, the option "max-instatement-indent" may need to be increased. If you are not getting the paren and square bracket alignment you want, try increasing - this value. The default minimum is 40 and the maximum is 120. -

+ this value. The default minimum is 40 and the maximum is 120.

A new bracket style option, "style=google", has been added. It uses attached brackets and indents the class access modifiers one-half indent.  A complete description of the Google style is available at the google‑styleguide website (https://code.google.com/p/google-styleguide/). The website has standards for several programming languages - along with a python program to verify the style and an emacs script for using the style. -

+ along with a python program to verify the style and an emacs script for using the style.

A new indent option "indent-modifiers" will indent class access modifiers (public, protected, or 'private) one-half - indent. The rest of the class is not indented. It is described in the "Indentation Options" section of the documentation. -

+ indent. The rest of the class is not indented. It is described in the "Indentation Options" section of the + documentation.

Four new bracket modify options, "attach-namespaces", "attach-classes", "attach-inlines", and "attach-extern-c", can be used to modify your selected bracket style. They are described in a new "Bracket Modify Options" section - of the documentation. -

+ of the documentation.

A new option, "remove-brackets", will remove brackets from conditional statements. The statement must be a single - statement on a single line. It is described in the "Formatting Options" section of the documentation. -

+ statement on a single line. It is described in the "Formatting Options" section of the documentation.

A new option, "indent-preproc-cond", will indent preprocessor conditional statements (#if #elif, #else, #endif). It is described in the "Indentation Options" section of the documentation. The option "indent-preprocessor" has been deprecated and will be removed in a future release. Use "indent-preproc-define" instead. The processing of - preprocessor #define statements has not changed. -

+ preprocessor #define statements has not changed.

A new option, "remove-comment-prefix", will remove a leading '*' from multi-line comments. It is described in the "Formatting Options" section of the documentation. With the syntax coloring of modern editors a leading '*' @@ -183,125 +348,102 @@ The idea is that a style that is hard to maintain will discourage modification and updating. The converted style should retain most of the formatting within the comment and result in a comment that is easier to maintain. For consistency the option also indents multi-line comments that are not preceded by the '*'. This may slightly modify - the indentation of any commented-out code. -

+ the indentation of any commented-out code.

The option "pad-first-paren-out" was fixed to not pad if the following paren is empty. This makes the option consistent with "pad-paren-out". To fix empty parens that have been padded run with the option "unpad-paren" in addition - to "pad-first-paren-out". This needs to be done only once. -

+ to "pad-first-paren-out". This needs to be done only once.

- Processing of C++11 raw string literals has been added. -

+ Processing of C++11 raw string literals has been added.

The compiler definition ASTYLE_NO_VCX (no Visual Studio exports) has been changed to ASTYLE_NO_EXPORTS and can be used with any Windows compiler. The Clang compiler needs this option to avoid errors on dynamic libraries. It removes the "__declspec(dllexport)" - definition from exported functions. Linux compilers do not use this. -

+ definition from exported functions. Linux compilers do not use this.

A new shared object (DLL) entry point, AStyleMainUtf16, has been added for processing C# UTF-16 strings. C# does not have built in functions for converting the UTF-16 strings to UTF-8. This entry point will accept UTF-16 strings, format the source code, and return UTF-16 strings. The error handling function and version number still use UTF-8 strings. The C# example program in the "Developer Information" shows the new calling procedure. Changes from the - previous release are marked in the example. -

+ previous release are marked in the example.

C# strings are UTF-16 on both Windows and Linux. C# does not use the UTF-32 wchar_t strings on Linux. Qt also uses UTF-16 on both Windows and Linux, but has built in UTF-8 conversion functions. Qt strings can be converted to UTF-8 by Qt, or the new entry point can be used. There may be other "managed code" applications on Linux that - use UTF-16. -

+ use UTF-16.

The "Links" page has two new sections for links mentioned in previous versions of Artistic Style. It links to - free software and other information. -

+ free software and other information.

The "Developer Information" section has a new example and download for calling Artistic Style from an Objective‑C program. Since it is another "C" language the only thing needed is to link the program with a library build of Artistic Style. The example was developed on Windows and Linux using the GNUstep project. Since the example is a console program the problems with the GNUstep GUI have been avoided. It has not been tested on a Mac, but should be close to working. The "Developer Information" section also has new page for "Objective‑C on Windows and - Linux" which has information on compiling and running the example on those systems. -

+ Linux" which has information on compiling and running the example on those systems.

The executable included in the Windows distribution was compiled with Visual Studio 2010 (platform toolset v100). Higher releases contain dependencies on Windows API functions that exist only on Windows Vista, Windows 7, and Windows 8. This means that applications built with a Visual Studio 2012 C++ compiler would fail to load and execute - on Windows XP. -

+ on Windows XP.

If you are using Windows Vista or higher, and have a Visual Studio 2012 or higher compiler available, recompiling will probably result in faster execution. If you use a compiler other than Visual Studio, you can probably get better execution by compiling using the C++11 standards. Artistic Style uses a lot of string vectors and the new - move semantics will probably result in faster execution. -

+ move semantics will probably result in faster execution.

- Thanks to Evmenov Georgiy, Matthew Woehlke, Jiang, Ruzzz, and beta100100 for their contributions. -

+ Thanks to Evmenov Georgiy, Matthew Woehlke, Jiang, Ruzzz, and beta100100 for their contributions.

Artistic Style 2.03  (April 2013)

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. -

+ Style. You may want to format your source before making program changes in order to bring it up to date.

A new option, "max-code-length=#" or "xC#", will limit the length of code on a line. A new option "break‑after‑logical", - or "xL", will modify a line break for conditionals. See the documentation for details. -

+ or "xL", will modify a line break for conditionals. See the documentation for details.

A new option, "pad-first-paren-out" or "xd", will pad only the first paren in a series on the outside. See the - documentation for details. -

+ documentation for details.

A new option, "indent=force-tab-tab=#" or "xT#", will allow force tab indents with a tab length that is different - than the indent length. See the documentation for details. -

+ than the indent length. See the documentation for details.

- The short option for delete-empty-lines has changed from "xd" to "xe". -

+ The short option for delete-empty-lines has changed from "xd" to "xe".

The C++11 standard for range-based "for" loops, "enum" with a base type, and rvalue references is now supported. The formatting of rvalue references is determined from the existing "align-pointer" and "align-reference" - options. -

+ options.

Closing the ending angle brackets of templates is now allowed by the C++11 standard. A new option, "close-templates" or "xy", will close the whitespace in the angle brackets of template definitions. Be sure your compiler supports - this before making the changes. -

+ this before making the changes.

- The C/C++ keyword 'extern "C"' in a preprocessor no longer causes an extra indent. -

+ The C/C++ keyword 'extern "C"' in a preprocessor no longer causes an extra indent.

Formatting of C++/CLI managed pointers (the '^' character) has been added to the "align-pointer" - option. -

+ option.

 The breaking of switch "default" statements has been fixed. The "default" statements - that have been incorrectly broken will be fixed in this release. -

+ that have been incorrectly broken will be fixed in this release.

The byte order mark (BOM) has been removed from ASLocalizer.cpp for all platforms. The encoding of the file is UTF-8. Many Windows editors can now recognize UTF-8 encoding without the BOM. Visual Studio has an option that needs to be set. With others. such as CodeBlocks, identification is automatic. On Linux, UTF-8 is the default - encoding. -

+ encoding.

Translations have been added for Dutch, Finnish, Italian, Japanese, Korean, Polish, Portuguese, Russian, Swedish, and Ukrainian. The translations were done with an automated translation program, Google Translate, so they may not be the best translation possible. The translations are at the end of ASLocalizer.cpp in the form of an English‑Translation pair. If you correct a translation, send the source as a bug report and it will be included in the next release. To add a language, see "Internationalization" in the "General Information" section of the documentation. Send - the addition as a bug report and it will be included in the next release. -

+ the addition as a bug report and it will be included in the next release.

There is a new Linux makefile for the Clang Compiler. Clang is a free compiler can be installed as a package on many Linux distributions. Some of its features are fast compiles, low memory use, expressive diagnostic messages, and GCC compatibility. It includes a static analyzer tool that finds potential bugs in your source code. An experimental - version can be installed on a Windows platform. There is more information in the Install Information documentation. -

+ version can be installed on a Windows platform. There is more information in the Install Information + documentation.

Visual Studio automatically creates an import library and an export file when you link a program that contains exports. It will do this for even a static library if it contains a __declspec(dllexport) definition. The Artistic @@ -310,32 +452,28 @@ to eliminate the files from the output. Use this only for static libraries or when the AStyle source is included in the compile. Do NOT use this when compiled as a shared (dynamic) library. It is effective only for Visual Studio 2012. It will NOT work with previous versions. It has no effect with other compilers since they require a separate - option to create the import library and export files. -

+ option to create the import library and export files.

The executable included in the Windows distribution was compiled with Visual Studio 2010 (platform toolset v100). Visual Studio 2012 (platform toolset v110) contains dependencies on Windows API functions that exist only on Windows Vista, Windows 7, and Windows 8. This means that applications built with a Visual Studio 2012 C++ compiler would fail to load and execute on Windows XP. Artistic Style was therefore compiled with Visual Studio 2010 to work - on computers using Windows XP. -

+ on computers using Windows XP.

If you are using Windows Vista or higher, and have the Visual Studio 2012 compiler available, recompiling with Visual Studio 2012 will probably result in faster execution. The Windows distribution has Visual Studio 2012 project - files available. -

+ files available.

If you use a compiler other than Visual Studio, you can probably get better execution by compiling using the C++11 standards. Artistic Style uses a lot of string vectors and the new move semantics will probably result in faster - execution. (To use C++11 on GCC and MinGW use the option --std=c++0x). This may change on future compiler releases.). -

+ execution. (To use C++11 on GCC and MinGW use the option --std=c++0x). This may change on future compiler + releases.

The "Developer Information" page has a new example and download for calling Artistic Style from a Python script. It will run with both Python 2 and Python 3. Using Python 3 shows an example of formatting a Unicode string with Artistic Style. Unicode strings must be encoded to UTF-8 before formatting and decoded back to Unicode afterward. The example script shows the technique for doing this. It also shows how to set up the function pointers and allocate - memory in Python. -

+ memory in Python.

If you use Visual Studio on Windows, it can now be used for Python development. Python Tools for Visual Studio (PTVS) is a free and open source plug-in for Visual Studio 2010 that supports Python and Iron Python. Other interpreters @@ -343,52 +481,23 @@ best thing is the Visual Studio debugging support using the .NET debugger and the normal Visual Studio debugger. It enables you to set break points, step through functions, change the current statement, inspect local variables, and perform other operations while debugging. It is best to use it with a project file, a minor irritation for - single page scripts. And there are some minor bugs. But overall it works quite well. -

+ single page scripts. And there are some minor bugs. But overall it works quite well.

- Thanks to Christopher Sean Morrison, Keith OHara, louis6g, and J for their contributions. -

+ Thanks to Christopher Sean Morrison, Keith OHara, louis6g, and J for their contributions.

-   -

+  

- Previous releases are available in the News Archives. -

+ Previous releases are available in the + News Archives.

-   -

+  

-
+

- -

+

-   -

- - - - - - - - - - +  

diff --git a/doc/notes.html b/doc/notes.html index 386f930..3efc52c 100644 --- a/doc/notes.html +++ b/doc/notes.html @@ -1,6 +1,6 @@ - + - + Artistic Style - Release Notes @@ -15,8 +15,40 @@

Artistic Style Release Notes

-   -

+  

+ +

Artistic Style 2.06  (Pending)

+ +
    +
  • Add new Objective‑C options "pad-return-type" (-xq) and "unpad-return-type" (-xr).
  • +
  • Add new option pad-comma (#100).
  • +
  • Add removing spaces before a comma (#100).
  • +
  • Add formatting of C++14 single-quote digit separators (#337).
  • +
  • Add translations for Bulgarian, Estonian, Greek, Hungarian, Norwegian, and Romanian.
  • +
  • Remove lineend option from formatCinToCout function, only Windows lineends are allowed.
  • +
  • Improve align-method-colon and apply to Objective‑C method calls.
  • +
  • Improve recognition of header guards in preprocessor statememts.
  • +
  • Improve recognition of C++11 uniform initializer brackets (#381).
  • +
  • Change align-method-colon short first line to align on the longest line instead of the first line.
  • +
  • Fix not recognizing an escaped space character within a quote (#403).
  • +
  • Fix attaching "if" statements to a #else preprocessor directive (#356).
  • +
  • Fix not clearing global variables for a new file (#364).
  • +
  • Fix not recognizing an rvalue reference in a template (#404).
  • +
  • Fix C# to recognize "using" as a header.
  • +
  • Fix C# to always recognize "forever" as a header.
  • +
  • Fix end of line comments for "pad-method-prefix" and "unpad-method-prefix".
  • +
  • Fix end of line comments for "pad-method-colon".
  • +
  • Refactoring: +
      +
    • Consolidate scattered ASFormatter conditional statements into a padParenObjC method.
    • +
    • Remove ASBase methods from being inlined as class definitions.
    • +
    • Replace C char arrays in astyle_main.cpp with C++ strings.
    • +
    • Return language translation as a mutable variable.
    • +
    • Portability changes for additional compiler support (#352).
    • +
    • Minor changes based on results of the Clang-Tidy.
    • +
    +
  • +

Artistic Style 2.05.1  (December 2014)

@@ -39,7 +71,7 @@
  • Add new option, "dry-run", to run AStyle without updating the files (#184, #285).
  • Add new options, "html" (-!") and "html=###", to display the HTML help documentation in the default browser.
  • -
  • Add tags "*INDENT-OFF*" and "*INDENT_ON*" to disable formatting of source code blocks +
  • Add tags "*INDENT-OFF*" and "*INDENT_ON*" to disable formatting of source code blocks (#2, #47, #55, #78, #110, #176).
  • Add tag *NOPAD* to disable selected formatting on a single line.
  • Add '__attribute__ ((visibility ("default")))' to Linux exported functions.
  • @@ -79,7 +111,7 @@
  • Fix indentation of C# "let" statements.
  • Fix a few omissions with "fill-empty-lines".
  • Fix file read to read 64K blocks of data.
  • -
  • Refactor to un-obfuscate (clarify) the code, and improve design and decomposition:: +
  • Refactor to un-obfuscate (clarify) the code, and improve design and decomposition:
    • Extract class Utf8_16 from ASConsole.
    • Replace Linux dependency on iconv with a Utf8_16 class for ASLibrary.
    • @@ -234,47 +266,19 @@

    -   -

    +  

    Previous releases are available in the Release - Notes Archives. -

    + Notes Archives.

    -   -

    +  

    -
    +

    - -

    +

    -   -

    - - - - - - - - - - +  

    diff --git a/doc/styles.css b/doc/styles.css index 127fd79..892ca1c 100644 --- a/doc/styles.css +++ b/doc/styles.css @@ -7,7 +7,6 @@ * p.contents entries are for the table of contents * a.contents are table of contents links (not underlined) * a.links are links (underlined) - * .footer is the image table at the bottom of the page * img does not have a border * pre is a predefined format for formatting code */ @@ -19,7 +18,7 @@ h1 { color: #0000A0; text-align: center; font-style: italic; margin-top: 18pt; m h2.large { color: #0000A0; text-align: center; font-size: x-large; margin-top: 0.4in; margin-left: -0.5in; } h2 { color: #0000A0; text-align: center; font-size: larger; margin-top: 0.4in; margin-left: -0.5in; } h3 { color: #0000A0; margin-top: 0.4in; margin-left: -0.4in; } -h4 { color: #0000A0; } +h4 { color: #0000A0; margin-top: 0.3in; } p.noindent { margin-left: -0.4in; } p.contents1 { font-size: 105%; margin-top: 0in; margin-left: 0in; margin-bottom: 0in; margin-right: 0in; } @@ -31,9 +30,6 @@ a.contents:hover { color: #F00000; text-decoration: none; } a:link, a:visited { color: #0000A0; text-decoration: underline; } a:hover { color: #F00000; text-decoration: underline; } -center.footer { margin-left: -0.4in; margin-top: 0.25in; } -h2.footer { font-size: x-large; margin-top: 0; margin-left: 0; } - img { border: none; } pre { margin-left: 0.3in; color: navy; font-weight: bold; } diff --git a/makefile/clang/Makefile b/makefile/clang/Makefile index f6704e8..c36114d 100644 --- a/makefile/clang/Makefile +++ b/makefile/clang/Makefile @@ -1,7 +1,6 @@ # Make file for GCC compiler on Linux or compatible OS -# The license.html file describes the conditions under which this software may be distributed. -# list of source files +# list of source files for astyle SRC = astyle_main.cpp \ ASBeautifier.cpp \ ASFormatter.cpp \ @@ -9,6 +8,13 @@ SRC = astyle_main.cpp \ ASLocalizer.cpp \ ASResource.cpp +# list of source files for libraries without ASLocalizer +SRCx = astyle_main.cpp \ + ASBeautifier.cpp \ + ASFormatter.cpp \ + ASEnhancer.cpp \ + ASResource.cpp + # source directories vpath %.cpp ../../src vpath %.h ../../src @@ -24,15 +30,12 @@ ifndef prefix prefix=/usr endif 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 +CBASEFLAGS = -Wall -Wextra -fno-rtti -fno-exceptions JAVAINCS = -I$(JAVA_HOME)/include CXX = clang++ INSTALL=install -o $(USER) -g $(USER) @@ -67,54 +70,54 @@ endif # a suffix is added for each build OBJ = $(patsubst %.cpp,$(objdir)/%.o,$(SRC)) OBJd = $(patsubst %.cpp,$(objdir)/%_d.o,$(SRC)) -OBJs = $(patsubst %.cpp,$(objdir)/%_s.o,$(SRC)) -OBJsd = $(patsubst %.cpp,$(objdir)/%_sd.o,$(SRC)) -OBJa = $(patsubst %.cpp,$(objdir)/%_a.o,$(SRC)) -OBJad = $(patsubst %.cpp,$(objdir)/%_ad.o,$(SRC)) -OBJsj = $(patsubst %.cpp,$(objdir)/%_sj.o,$(SRC)) -OBJsjd = $(patsubst %.cpp,$(objdir)/%_sjd.o,$(SRC)) +OBJs = $(patsubst %.cpp,$(objdir)/%_s.o,$(SRCx)) +OBJsd = $(patsubst %.cpp,$(objdir)/%_sd.o,$(SRCx)) +OBJa = $(patsubst %.cpp,$(objdir)/%_a.o,$(SRCx)) +OBJad = $(patsubst %.cpp,$(objdir)/%_ad.o,$(SRCx)) +OBJsj = $(patsubst %.cpp,$(objdir)/%_sj.o,$(SRCx)) +OBJsjd = $(patsubst %.cpp,$(objdir)/%_sjd.o,$(SRCx)) # define object file rule (with the suffix) for each build # OBJ $(objdir)/%.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSr) -c -o $@ $< + $(CXX) $(CFLAGSr) -c $< -o $@ # OBJd $(objdir)/%_d.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSd) -c -o $@ $< + $(CXX) $(CFLAGSd) -c $< -o $@ # OBJs $(objdir)/%_s.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSs) -c -o $@ $< + $(CXX) $(CFLAGSs) -c $< -o $@ # OBJsd $(objdir)/%_sd.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsd) -c -o $@ $< + $(CXX) $(CFLAGSsd) -c $< -o $@ # OBJa $(objdir)/%_a.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSa) -c -o $@ $< + $(CXX) $(CFLAGSa) -c $< -o $@ # OBJad $(objdir)/%_ad.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSad) -c -o $@ $< + $(CXX) $(CFLAGSad) -c $< -o $@ # OBJsj $(objdir)/%_sj.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsj) -c -o $@ $< + $(CXX) $(CFLAGSsj) -c $< -o $@ # OBJsjd $(objdir)/%_sjd.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsjd) -c -o $@ $< + $(CXX) $(CFLAGSsjd) -c $< -o $@ ################################################## # define build dependencies for each command @@ -131,16 +134,16 @@ astyled: $(OBJd) $(CXX) $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo -shared: libastyle-2.05.1.so -libastyle-2.05.1.so: $(OBJs) +shared: libastyle.so +libastyle.so: $(OBJs) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/libastyle-2.06.so $^ @ echo -shareddebug: libastyle-2.05.1d.so -libastyle-2.05.1d.so: $(OBJsd) +shareddebug: libastyled.so +libastyled.so: $(OBJsd) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/libastyle-2.06d.so $^ @ echo static: libastyle.a @@ -155,16 +158,16 @@ libastyled.a: $(OBJad) ar crs $(bindir)/$@ $^ @ echo -java: libastyle-2.05.1j.so -libastyle-2.05.1j.so: $(OBJsj) +java: libastylej.so +libastylej.so: $(OBJsj) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/libastyle-2.06j.so $^ @ echo -javadebug: libastyle-2.05.1jd.so -libastyle-2.05.1jd.so: $(OBJsjd) +javadebug: libastylejd.so +libastylejd.so: $(OBJsjd) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/libastyle-2.06jd.so $^ @ echo all: release debug shared shareddebug static staticdebug @@ -181,19 +184,17 @@ install: $(INSTALL) -m 755 -d $(ipath) @$(INSTALL) -m 755 $(bindir)/astyle $(ipath) + @if [ -d $(SYSCONF_PATH)/html ]; then \ + rm -rf $(SYSCONF_PATH)/html; \ + fi + $(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)/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 --git a/makefile/gcc/Makefile b/makefile/gcc/Makefile index b1af4c1..59c7457 100644 --- a/makefile/gcc/Makefile +++ b/makefile/gcc/Makefile @@ -1,7 +1,6 @@ # Make file for GCC compiler on Linux or compatible OS -# The license.html file describes the conditions under which this software may be distributed. -# list of source files +# list of source files for astyle SRC = astyle_main.cpp \ ASBeautifier.cpp \ ASFormatter.cpp \ @@ -9,6 +8,13 @@ SRC = astyle_main.cpp \ ASLocalizer.cpp \ ASResource.cpp +# list of source files for libraries without ASLocalizer +SRCx = astyle_main.cpp \ + ASBeautifier.cpp \ + ASFormatter.cpp \ + ASEnhancer.cpp \ + ASResource.cpp + # source directories vpath %.cpp ../../src vpath %.h ../../src @@ -24,15 +30,12 @@ ifndef prefix prefix=/usr endif 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 +CBASEFLAGS = -Wall -Wextra -fno-rtti -fno-exceptions JAVAINCS = -I$(JAVA_HOME)/include CXX = g++ INSTALL=install -o $(USER) -g $(USER) @@ -67,54 +70,54 @@ endif # a suffix is added for each build OBJ = $(patsubst %.cpp,$(objdir)/%.o,$(SRC)) OBJd = $(patsubst %.cpp,$(objdir)/%_d.o,$(SRC)) -OBJs = $(patsubst %.cpp,$(objdir)/%_s.o,$(SRC)) -OBJsd = $(patsubst %.cpp,$(objdir)/%_sd.o,$(SRC)) -OBJa = $(patsubst %.cpp,$(objdir)/%_a.o,$(SRC)) -OBJad = $(patsubst %.cpp,$(objdir)/%_ad.o,$(SRC)) -OBJsj = $(patsubst %.cpp,$(objdir)/%_sj.o,$(SRC)) -OBJsjd = $(patsubst %.cpp,$(objdir)/%_sjd.o,$(SRC)) +OBJs = $(patsubst %.cpp,$(objdir)/%_s.o,$(SRCx)) +OBJsd = $(patsubst %.cpp,$(objdir)/%_sd.o,$(SRCx)) +OBJa = $(patsubst %.cpp,$(objdir)/%_a.o,$(SRCx)) +OBJad = $(patsubst %.cpp,$(objdir)/%_ad.o,$(SRCx)) +OBJsj = $(patsubst %.cpp,$(objdir)/%_sj.o,$(SRCx)) +OBJsjd = $(patsubst %.cpp,$(objdir)/%_sjd.o,$(SRCx)) # define object file rule (with the suffix) for each build # OBJ $(objdir)/%.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSr) -c -o $@ $< + $(CXX) $(CFLAGSr) -c $< -o $@ # OBJd $(objdir)/%_d.o: %.cpp astyle.h astyle_main.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSd) -c -o $@ $< + $(CXX) $(CFLAGSd) -c $< -o $@ # OBJs $(objdir)/%_s.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSs) -c -o $@ $< + $(CXX) $(CFLAGSs) -c $< -o $@ # OBJsd $(objdir)/%_sd.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsd) -c -o $@ $< + $(CXX) $(CFLAGSsd) -c $< -o $@ # OBJa $(objdir)/%_a.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSa) -c -o $@ $< + $(CXX) $(CFLAGSa) -c $< -o $@ # OBJad $(objdir)/%_ad.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSad) -c -o $@ $< + $(CXX) $(CFLAGSad) -c $< -o $@ # OBJsj $(objdir)/%_sj.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsj) -c -o $@ $< + $(CXX) $(CFLAGSsj) -c $< -o $@ # OBJsjd $(objdir)/%_sjd.o: %.cpp astyle.h @ mkdir -p $(objdir) - $(CXX) $(CFLAGSsjd) -c -o $@ $< + $(CXX) $(CFLAGSsjd) -c $< -o $@ ################################################## # define build dependencies for each command @@ -131,16 +134,16 @@ astyled: $(OBJd) $(CXX) $(LDFLAGSd) -o $(bindir)/$@ $^ @ echo -shared: libastyle-2.05.1.so -libastyle-2.05.1.so: $(OBJs) +shared: libastyle.so +libastyle.so: $(OBJs) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/libastyle-2.06.so $^ @ echo -shareddebug: libastyle-2.05.1d.so -libastyle-2.05.1d.so: $(OBJsd) +shareddebug: libastyled.so +libastyled.so: $(OBJsd) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/libastyle-2.06d.so $^ @ echo static: libastyle.a @@ -155,16 +158,16 @@ libastyled.a: $(OBJad) ar crs $(bindir)/$@ $^ @ echo -java: libastyle-2.05.1j.so -libastyle-2.05.1j.so: $(OBJsj) +java: libastylej.so +libastylej.so: $(OBJsj) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSr) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSr) -o $(bindir)/libastyle-2.06j.so $^ @ echo -javadebug: libastyle-2.05.1jd.so -libastyle-2.05.1jd.so: $(OBJsjd) +javadebug: libastylejd.so +libastylejd.so: $(OBJsjd) @ mkdir -p $(bindir) - $(CXX) -shared $(LDFLAGSd) -o $(bindir)/$@ $^ + $(CXX) -shared $(LDFLAGSd) -o $(bindir)/libastyle-2.06jd.so $^ @ echo all: release debug shared shareddebug static staticdebug @@ -181,19 +184,17 @@ install: $(INSTALL) -m 755 -d $(ipath) @$(INSTALL) -m 755 $(bindir)/astyle $(ipath) + @if [ -d $(SYSCONF_PATH)/html ]; then \ + rm -rf $(SYSCONF_PATH)/html; \ + fi + $(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)/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 --git a/src/ASBeautifier.cpp b/src/ASBeautifier.cpp index 086b037..61bf441 100644 --- a/src/ASBeautifier.cpp +++ b/src/ASBeautifier.cpp @@ -1,39 +1,29 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASBeautifier.cpp - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// ASBeautifier.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- #include "astyle.h" #include +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- namespace astyle { - +// // this must be global static int g_preprocessorCppExternCBracket; +//----------------------------------------------------------------------------- +// ASBeautifier class +//----------------------------------------------------------------------------- + /** * ASBeautifier's constructor * This constructor is called only once for each source file. @@ -41,8 +31,6 @@ static int g_preprocessorCppExternCBracket; */ ASBeautifier::ASBeautifier() { - g_preprocessorCppExternCBracket = 0; - waitingBeautifierStack = NULL; activeBeautifierStack = NULL; waitingBeautifierStackLengthStack = NULL; @@ -101,7 +89,7 @@ ASBeautifier::ASBeautifier() * * 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; @@ -158,6 +146,7 @@ ASBeautifier::ASBeautifier(const ASBeautifier &other) : ASBase(other) inLineNumber = other.inLineNumber; horstmannIndentInStatement = other.horstmannIndentInStatement; nonInStatementBracket = other.nonInStatementBracket; + objCColonAlignSubsequent = other.objCColonAlignSubsequent; lineCommentNoBeautify = other.lineCommentNoBeautify; isElseHeaderIndent = other.isElseHeaderIndent; isCaseHeaderCommentIndent = other.isCaseHeaderCommentIndent; @@ -302,6 +291,7 @@ void ASBeautifier::init(ASSourceIterator* iter) sourceIterator = iter; initVectors(); ASBase::init(getFileType()); + g_preprocessorCppExternCBracket = 0; initContainer(waitingBeautifierStack, new vector); initContainer(activeBeautifierStack, new vector); @@ -409,6 +399,7 @@ void ASBeautifier::init(ASSourceIterator* iter) inLineNumber = 0; horstmannIndentInStatement = 0; nonInStatementBracket = 0; + objCColonAlignSubsequent = 0; } /* @@ -736,6 +727,16 @@ bool ASBeautifier::getForceTabIndentation(void) const return shouldForceTabIndentation; } +/** +* Get the state of the Objective-C align method colon option. +* +* @return state of shouldAlignMethodColon option. +*/ +bool ASBeautifier::getAlignMethodColon(void) const +{ + return shouldAlignMethodColon; +} + /** * get the state of the block indentation option. * @@ -854,10 +855,10 @@ int ASBeautifier::getTabLength(void) const * @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 isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; + bool isInQuoteContinuation = isInVerbatimQuote || haveLineContinuationChar; currentHeader = NULL; lastLineHeader = NULL; @@ -965,7 +966,7 @@ string ASBeautifier::beautify(const string &originalLine) { if (isInIndentablePreprocBlock) return preLineWS(preprocBlockIndent, 0); - else if (!headerStack->empty() || isInEnum) + if (!headerStack->empty() || isInEnum) return preLineWS(prevFinalLineIndentCount, prevFinalLineSpaceIndentCount); // must fall thru here } @@ -1075,10 +1076,8 @@ string ASBeautifier::beautify(const string &originalLine) // and then remove it from the active beautifier stack and delete it. if (!backslashEndsPrevLine && isInDefineDefinition && !isInDefine) { - ASBeautifier* defineBeautifier; - isInDefineDefinition = false; - defineBeautifier = activeBeautifierStack->back(); + ASBeautifier* defineBeautifier = activeBeautifierStack->back(); activeBeautifierStack->pop_back(); string indentedLine = defineBeautifier->beautify(line); @@ -1099,6 +1098,7 @@ string ASBeautifier::beautify(const string &originalLine) activeBeautifierStack->back()->inLineNumber = inLineNumber; activeBeautifierStack->back()->horstmannIndentInStatement = horstmannIndentInStatement; activeBeautifierStack->back()->nonInStatementBracket = nonInStatementBracket; + activeBeautifierStack->back()->objCColonAlignSubsequent = objCColonAlignSubsequent; activeBeautifierStack->back()->lineCommentNoBeautify = lineCommentNoBeautify; activeBeautifierStack->back()->isElseHeaderIndent = isElseHeaderIndent; activeBeautifierStack->back()->isCaseHeaderCommentIndent = isCaseHeaderCommentIndent; @@ -1143,6 +1143,9 @@ string ASBeautifier::beautify(const string &originalLine) if (shouldAlignMethodColon) { colonIndentObjCMethodDefinition = line.find(':'); + int objCColonAlignSubsequentIndent = objCColonAlignSubsequent + indentLength; + if (objCColonAlignSubsequentIndent > colonIndentObjCMethodDefinition) + colonIndentObjCMethodDefinition = objCColonAlignSubsequentIndent; } else if (inStatementIndentStack->empty() || inStatementIndentStack->back() == 0) @@ -1209,10 +1212,10 @@ string ASBeautifier::beautify(const string &originalLine) return indentedLine; } -string &ASBeautifier::getIndentedLineReturn(string &newLine, const string &originalLine) const +string& ASBeautifier::getIndentedLineReturn(string& newLine, const string& originalLine) const { if (isIndentModeOff) - return const_cast(originalLine); + return const_cast(originalLine); return newLine; } @@ -1246,10 +1249,9 @@ string ASBeautifier::preLineWS(int lineIndentCount, int lineSpaceIndentCount) co /** * 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; int remainingCharNum = line.length() - i; int nextNonWSChar = getNextProgramCharDistance(line, i); @@ -1281,7 +1283,7 @@ void ASBeautifier::registerInStatementIndent(const string &line, int i, int spac tabIncrement += convertTabToSpaces(j, tabIncrement); } - inStatementIndent = i + nextNonWSChar + spaceTabCount_ + tabIncrement; + int inStatementIndent = i + nextNonWSChar + spaceTabCount_ + tabIncrement; // check for run-in statement if (i > 0 && line[0] == '{') @@ -1309,7 +1311,7 @@ void ASBeautifier::registerInStatementIndent(const string &line, int i, int spac /** * Register an in-statement indent for a class header or a class initializer colon. */ -void ASBeautifier::registerInStatementIndentColon(const string &line, int i, int tabIncrementIn) +void ASBeautifier::registerInStatementIndentColon(const string& line, int i, int tabIncrementIn) { assert(line[i] == ':'); assert(isInClassInitializer || isInClassHeaderTab); @@ -1351,7 +1353,7 @@ pair ASBeautifier::computePreprocessorIndent() * 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; @@ -1376,7 +1378,7 @@ int ASBeautifier::getNextProgramCharDistance(const string &line, int i) const { if (line.compare(i + charDistance, 2, "//") == 0) return remainingCharNum; - else if (line.compare(i + charDistance, 2, "/*") == 0) + if (line.compare(i + charDistance, 2, "/*") == 0) { charDistance++; inComment = true; @@ -1390,7 +1392,7 @@ int ASBeautifier::getNextProgramCharDistance(const string &line, int i) const } // 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)); @@ -1428,7 +1430,7 @@ const string* ASBeautifier::findHeader(const string &line, int i, } // 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])); @@ -1454,15 +1456,14 @@ const string* ASBeautifier::findOperator(const string &line, int i, * @param container a vector of strings. * @param element the element to find . */ -int ASBeautifier::indexOf(vector &container, const string* element) const +int ASBeautifier::indexOf(vector& container, const string* element) const { vector::const_iterator where; where = find(container.begin(), container.end(), element); if (where == container.end()) return -1; - else - return (int) (where - container.begin()); + return (int) (where - container.begin()); } /** @@ -1483,9 +1484,8 @@ int ASBeautifier::convertTabToSpaces(int i, int tabIncrementIn) const * @return the trimmed line. * @param str the line to trim. */ -string ASBeautifier::trim(const string &str) const +string ASBeautifier::trim(const string& str) const { - int start = 0; int end = str.length() - 1; @@ -1509,7 +1509,7 @@ string ASBeautifier::trim(const string &str) const * @return the trimmed line. * @param str the line to trim. */ -string ASBeautifier::rtrim(const string &str) const +string ASBeautifier::rtrim(const string& str) const { size_t len = str.length(); size_t end = str.find_last_not_of(" \t"); @@ -1524,7 +1524,7 @@ string ASBeautifier::rtrim(const string &str) const * 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; @@ -1560,7 +1560,7 @@ void ASBeautifier::deleteBeautifierVectors() * used for all vectors except tempStacks */ template -void ASBeautifier::deleteContainer(T &container) +void ASBeautifier::deleteContainer(T& container) { if (container != NULL) { @@ -1576,7 +1576,7 @@ void ASBeautifier::deleteContainer(T &container) * Therefore the ASBeautifier objects have to be deleted in addition to the * ASBeautifier pointer entries. */ -void ASBeautifier::deleteBeautifierContainer(vector* &container) +void ASBeautifier::deleteBeautifierContainer(vector*& container) { if (container != NULL) { @@ -1597,7 +1597,7 @@ void ASBeautifier::deleteBeautifierContainer(vector* &container) * The tempStacks is a vector of pointers to strings allocated with the 'new' operator. * Therefore the strings have to be deleted in addition to the tempStacks entries. */ -void ASBeautifier::deleteTempStacksContainer(vector*>* &container) +void ASBeautifier::deleteTempStacksContainer(vector*>*& container) { if (container != NULL) { @@ -1618,7 +1618,7 @@ void ASBeautifier::deleteTempStacksContainer(vector*>* &co * T is the type of vector 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 @@ -1632,7 +1632,7 @@ void ASBeautifier::initContainer(T &container, T value) * The tempStacks is a vector of pointers to strings allocated with the 'new' operator. * Any residual entries are deleted before the vector is initialized. */ -void ASBeautifier::initTempStacksContainer(vector*>* &container, +void ASBeautifier::initTempStacksContainer(vector*>*& container, vector*>* value) { if (container != NULL) @@ -1647,7 +1647,7 @@ void ASBeautifier::initTempStacksContainer(vector*>* &cont * * @return true if line ends with a comma, otherwise false. */ -bool ASBeautifier::statementEndsWithComma(const string &line, int index) const +bool ASBeautifier::statementEndsWithComma(const string& line, int index) const { assert(line[index] == '='); @@ -1685,7 +1685,8 @@ bool ASBeautifier::statementEndsWithComma(const string &line, int index) const continue; } - if (ch == '"' || ch == '\'') + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) { isInQuote_ = true; quoteChar_ = ch; @@ -1730,7 +1731,7 @@ bool ASBeautifier::statementEndsWithComma(const string &line, int index) const * * @return is before a line-end comment. */ -bool ASBeautifier::isLineEndComment(const string &line, int startPos) const +bool ASBeautifier::isLineEndComment(const string& line, int startPos) const { assert(line.compare(startPos, 2, "/*") == 0); @@ -1750,7 +1751,7 @@ bool ASBeautifier::isLineEndComment(const string &line, int startPos) const * * @return is the index to the previous word (the in statement indent). */ -int ASBeautifier::getInStatementIndentAssign(const string &line, size_t currPos) const +int ASBeautifier::getInStatementIndentAssign(const string& line, size_t currPos) const { assert(line[currPos] == '='); @@ -1778,7 +1779,7 @@ int ASBeautifier::getInStatementIndentAssign(const string &line, size_t currPos) * * @return is the indent to the second word on the line (the in statement indent). */ -int ASBeautifier::getInStatementIndentComma(const string &line, size_t currPos) const +int ASBeautifier::getInStatementIndentComma(const string& line, size_t currPos) const { assert(line[currPos] == ','); @@ -1811,7 +1812,7 @@ int ASBeautifier::getInStatementIndentComma(const string &line, size_t currPos) * * @return is the next word or an empty string if none found. */ -string ASBeautifier::getNextWord(const string &line, size_t currPos) const +string ASBeautifier::getNextWord(const string& line, size_t currPos) const { size_t lineLength = line.length(); // get the last legal word (may be a number) @@ -1839,7 +1840,7 @@ string ASBeautifier::getNextWord(const string &line, size_t currPos) const * * @return is true or false. */ -bool ASBeautifier::isIndentedPreprocessor(const string &line, size_t currPos) const +bool ASBeautifier::isIndentedPreprocessor(const string& line, size_t currPos) const { assert(line[0] == '#'); string nextWord = getNextWord(line, currPos); @@ -1885,7 +1886,7 @@ bool ASBeautifier::isIndentedPreprocessor(const string &line, size_t currPos) co * * @return is true or false. */ -bool ASBeautifier::isPreprocessorConditionalCplusplus(const string &line) const +bool ASBeautifier::isPreprocessorConditionalCplusplus(const string& line) const { string preproc = trim(line.substr(1)); if (preproc.compare(0, 5, "ifdef") == 0 && getNextWord(preproc, 4) == "__cplusplus") @@ -1917,7 +1918,7 @@ bool ASBeautifier::isPreprocessorConditionalCplusplus(const string &line) const * * @return is true or false. */ -bool ASBeautifier::isInPreprocessorUnterminatedComment(const string &line) +bool ASBeautifier::isInPreprocessorUnterminatedComment(const string& line) { if (!isInPreprocessorComment) { @@ -1952,7 +1953,7 @@ int ASBeautifier::getBeautifierFileType() const /** * Process preprocessor statements and update the beautifier stacks. */ -void ASBeautifier::processPreprocessor(const string &preproc, const string &line) +void ASBeautifier::processPreprocessor(const string& preproc, const string& line) { // When finding a multi-lined #define statement, the original beautifier // 1. sets its isInDefineDefinition flag @@ -1965,14 +1966,12 @@ void ASBeautifier::processPreprocessor(const string &preproc, const string &line { if (!isInDefineDefinition) { - ASBeautifier* defineBeautifier; - // this is the original beautifier isInDefineDefinition = true; // push a new beautifier into the active stack // this beautifier will be used for the indentation of this define - defineBeautifier = new ASBeautifier(*this); + ASBeautifier* defineBeautifier = new ASBeautifier(*this); activeBeautifierStack->push_back(defineBeautifier); } else @@ -2012,8 +2011,8 @@ void ASBeautifier::processPreprocessor(const string &preproc, const string &line } else if (preproc == "endif") { - int stackLength; - ASBeautifier* beautifier; + int stackLength = 0; + ASBeautifier* beautifier = NULL; if (waitingBeautifierStackLengthStack != NULL && !waitingBeautifierStackLengthStack->empty()) { @@ -2145,7 +2144,7 @@ void ASBeautifier::computePreliminaryIndentation() && (*headerStack)[headerStack->size() - 2] == &AS_CLASS && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET && lineBeginsWithCloseBracket - && bracketBlockStateStack->back() == true) + && bracketBlockStateStack->back()) --indentCount; // unindent an indented switch closing bracket... @@ -2283,7 +2282,7 @@ int ASBeautifier::adjustIndentCountForBreakElseIfComments() const * Extract a preprocessor statement without the #. * If a error occurs an empty string is returned. */ -string ASBeautifier::extractPreprocessorStatement(const string &line) const +string ASBeautifier::extractPreprocessorStatement(const string& line) const { string preproc; size_t start = line.find_first_not_of("#/ \t"); @@ -2305,6 +2304,7 @@ void ASBeautifier::clearObjCMethodDefinitionAlignment() spaceIndentCount = 0; spaceIndentObjCMethodDefinition = 0; colonIndentObjCMethodDefinition = 0; + objCColonAlignSubsequent = 0; isInObjCMethodDefinition = false; isImmediatelyPostObjCMethodDefinition = false; if (!inStatementIndentStack->empty()) @@ -2317,7 +2317,7 @@ void ASBeautifier::clearObjCMethodDefinitionAlignment() * If it cannot be aligned indentLength is returned and a new colon * position is calculated. */ -int ASBeautifier::computeObjCColonAlignment(string &line, int colonAlignPosition) const +int ASBeautifier::computeObjCColonAlignment(string& line, int colonAlignPosition) const { int colonPosition = line.find(':'); if (colonPosition < 0 || colonPosition > colonAlignPosition) @@ -2328,7 +2328,7 @@ int ASBeautifier::computeObjCColonAlignment(string &line, int colonAlignPosition /** * Parse the current line to update indentCount and spaceIndentCount. */ -void ASBeautifier::parseCurrentLine(const string &line) +void ASBeautifier::parseCurrentLine(const string& line) { bool isInLineComment = false; bool isInOperator = false; @@ -2347,15 +2347,7 @@ void ASBeautifier::parseCurrentLine(const string &line) if (isInBeautifySQL) continue; - if (isWhiteSpace(ch)) - { - if (ch == '\t') - tabIncrementIn += convertTabToSpaces(i, tabIncrementIn); - continue; - } - // handle special characters (i.e. backslash+character such as \n, \t, ...) - if (isInQuote && !isInVerbatimQuote) { if (isSpecialChar) @@ -2380,8 +2372,18 @@ void ASBeautifier::parseCurrentLine(const string &line) else if (isInDefine && ch == '\\') continue; + // bypass whitespace here + if (isWhiteSpace(ch)) + { + if (ch == '\t') + tabIncrementIn += convertTabToSpaces(i, tabIncrementIn); + continue; + } + // handle quotes (such as 'x' and "Hello Dolly") - if (!(isInComment || isInLineComment) && (ch == '"' || ch == '\'')) + if (!(isInComment || isInLineComment) + && (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i)))) { if (!isInQuote) { @@ -2807,11 +2809,15 @@ void ASBeautifier::parseCurrentLine(const string &line) const string* newHeader = findHeader(line, i, headers); // Qt headers may be variables in C++ - if (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH) + if (isCStyle() + && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) { if (line.find_first_of("=;", i) != string::npos) newHeader = NULL; } + else if (newHeader == &AS_USING + && ASBeautifier::peekNextChar(line, i + (*newHeader).length() - 1) != '(') + newHeader = NULL; if (newHeader != NULL) { @@ -2820,10 +2826,8 @@ void ASBeautifier::parseCurrentLine(const string &line) isInHeader = true; - vector* lastTempStack; - if (tempStacks->empty()) - lastTempStack = NULL; - else + vector* lastTempStack = NULL;; + if (!tempStacks->empty()) lastTempStack = tempStacks->back(); // if a new block is opened, push a new stack into tempStacks to hold the @@ -3027,8 +3031,7 @@ void ASBeautifier::parseCurrentLine(const string &line) } else if (isDigit(peekNextChar(line, i))) { - // found a bit field - // so do nothing special + // found a bit field - do nothing special } else if (isCStyle() && isInClass && prevNonSpaceCh != ')') { @@ -3477,5 +3480,4 @@ void ASBeautifier::parseCurrentLine(const string &line) } // end of for loop * end of for loop * end of for loop * end of for loop * end of for loop * } - } // end namespace astyle diff --git a/src/ASEnhancer.cpp b/src/ASEnhancer.cpp index 808681b..eefec6d 100644 --- a/src/ASEnhancer.cpp +++ b/src/ASEnhancer.cpp @@ -1,33 +1,23 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASEnhancer.cpp - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// ASEnhancer.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- #include "astyle.h" +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- namespace astyle { +// +//----------------------------------------------------------------------------- +// ASEnhancer class +//----------------------------------------------------------------------------- /** * ASEnhancer constructor @@ -108,7 +98,7 @@ void ASEnhancer::init(int _fileType, * * @param line the original formatted line will be updated if necessary. */ -void ASEnhancer::enhance(string &line, bool isInNamespace, bool isInPreprocessor, bool isInSQL) +void ASEnhancer::enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL) { shouldUnindentLine = true; shouldUnindentComment = false; @@ -174,7 +164,7 @@ void ASEnhancer::enhance(string &line, bool isInNamespace, bool isInPreprocessor * * @param line a reference to the line that will be converted. */ -void ASEnhancer::convertForceTabIndentToSpaces(string &line) const +void ASEnhancer::convertForceTabIndentToSpaces(string& line) const { // replace tab indents with spaces for (size_t i = 0; i < line.length(); i++) @@ -195,15 +185,14 @@ void ASEnhancer::convertForceTabIndentToSpaces(string &line) const * * @param line a reference to the line that will be converted. */ -void ASEnhancer::convertSpaceIndentToForceTab(string &line) const +void ASEnhancer::convertSpaceIndentToForceTab(string& line) const { assert(tabLength > 0); // replace leading spaces with tab indents size_t newSpaceIndentLength = line.find_first_not_of(" \t"); size_t tabCount = newSpaceIndentLength / tabLength; // truncate extra spaces - line.erase(0U, tabCount * tabLength); - line.insert(0U, tabCount, '\t'); + line.replace(0U, tabCount * tabLength, tabCount, '\t'); } /** @@ -213,7 +202,7 @@ void ASEnhancer::convertSpaceIndentToForceTab(string &line) const * @param caseIndex 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; @@ -238,7 +227,8 @@ size_t ASEnhancer::findCaseColon(string &line, size_t caseIndex) const continue; // must close quote before continuing } } - if (line[i] == '\'' || line[i] == '\"') // check opening quote + if (line[i] == '"' // check opening quote + || (line[i] == '\'' && !isDigitSeparator(line, i))) { isInQuote_ = true; quoteChar_ = line[i]; @@ -263,13 +253,13 @@ size_t ASEnhancer::findCaseColon(string &line, size_t caseIndex) const * @param indent 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) return 0; - size_t charsToInsert; + size_t charsToInsert = 0; if (forceTab && indentLength != tabLength) { @@ -277,19 +267,19 @@ int ASEnhancer::indentLine(string &line, int indent) const convertForceTabIndentToSpaces(line); // insert the space indents charsToInsert = indent * indentLength; - line.insert(0U, charsToInsert, ' '); + line.insert(line.begin(), charsToInsert, ' '); // replace leading spaces with tab indents convertSpaceIndentToForceTab(line); } else if (useTabs) { charsToInsert = indent; - line.insert(0U, charsToInsert, '\t'); + line.insert(line.begin(), charsToInsert, '\t'); } else // spaces { charsToInsert = indent * indentLength; - line.insert(0U, charsToInsert, ' '); + line.insert(line.begin(), charsToInsert, ' '); } return charsToInsert; @@ -303,7 +293,7 @@ int ASEnhancer::indentLine(string &line, int indent) const * @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; @@ -352,7 +342,7 @@ bool ASEnhancer::isBeginDeclareSectionSQL(string &line, size_t index) const * @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; @@ -401,7 +391,7 @@ bool ASEnhancer::isEndDeclareSectionSQL(string &line, size_t index) const * @return false = one-line bracket has not been reached. * true = one-line bracket has been reached. */ -bool ASEnhancer::isOneLineBlockReached(string &line, int startChar) const +bool ASEnhancer::isOneLineBlockReached(string& line, int startChar) const { assert(line[startChar] == '{'); @@ -439,7 +429,8 @@ bool ASEnhancer::isOneLineBlockReached(string &line, int startChar) const continue; } - if (ch == '"' || ch == '\'') + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) { isInQuote_ = true; quoteChar_ = ch; @@ -472,7 +463,7 @@ bool ASEnhancer::isOneLineBlockReached(string &line, int startChar) const * parse characters in the current line to determine if an indent * or unindent is needed. */ -void ASEnhancer::parseCurrentLine(string &line, bool isInPreprocessor, bool isInSQL) +void ASEnhancer::parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL) { bool isSpecialChar = false; // is a backslash escape character @@ -502,7 +493,9 @@ void ASEnhancer::parseCurrentLine(string &line, bool isInPreprocessor, bool isIn } // handle quotes (such as 'x' and "Hello Dolly") - if (!isInComment && (ch == '"' || ch == '\'')) + if (!isInComment + && (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i)))) { if (!isInQuote) { @@ -665,7 +658,7 @@ void ASEnhancer::parseCurrentLine(string &line, bool isInPreprocessor, bool isIn * @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); @@ -754,7 +747,7 @@ size_t ASEnhancer::processSwitchBlock(string &line, size_t index) * @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"); @@ -800,5 +793,4 @@ int ASEnhancer::unindentLine(string &line, int unindent) const return charsToErase; } - } // end namespace astyle diff --git a/src/ASFormatter.cpp b/src/ASFormatter.cpp index 54159d3..c41ffe8 100644 --- a/src/ASFormatter.cpp +++ b/src/ASFormatter.cpp @@ -1,36 +1,27 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASFormatter.cpp - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// ASFormatter.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- #include "astyle.h" #include #include +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- namespace astyle { +// +//----------------------------------------------------------------------------- +// ASFormatter class +//----------------------------------------------------------------------------- + /** * Constructor of ASFormatter */ @@ -51,6 +42,7 @@ ASFormatter::ASFormatter() objCColonPadMode = COLON_PAD_NO_CHANGE; lineEnd = LINEEND_DEFAULT; maxCodeLength = string::npos; + shouldPadCommas = false; shouldPadOperators = false; shouldPadParensOutside = false; shouldPadFirstParen = false; @@ -81,6 +73,8 @@ ASFormatter::ASFormatter() shouldPadMethodColon = false; shouldPadMethodPrefix = false; shouldUnPadMethodPrefix = false; + shouldPadReturnType = false; + shouldUnPadReturnType = false; // initialize ASFormatter member vectors formatterFileType = 9; // reset to an invalid type @@ -148,7 +142,7 @@ void ASFormatter::init(ASSourceIterator* si) enhancer->init(getFileType(), getIndentLength(), getTabLength(), - getIndentString() == "\t" ? true : false, + getIndentString() == "\t", getForceTabIndentation(), getNamespaceIndent(), getCaseIndent(), @@ -187,6 +181,7 @@ void ASFormatter::init(ASSourceIterator* si) preprocBracketTypeStackSize = 0; spacePadNum = 0; nextLineSpacePadNum = 0; + objCColonAlign = 0; templateDepth = 0; squareBracketCount = 0; horstmannIndentChars = 0; @@ -251,6 +246,7 @@ void ASFormatter::init(ASSourceIterator* si) isImmediatelyPostComment = false; isImmediatelyPostLineComment = false; isImmediatelyPostEmptyBlock = false; + isImmediatelyPostObjCMethodPrefix = false; isImmediatelyPostPreprocessor = false; isImmediatelyPostReturn = false; isImmediatelyPostThrow = false; @@ -267,8 +263,9 @@ void ASFormatter::init(ASSourceIterator* si) isCharImmediatelyPostCloseBlock = false; isCharImmediatelyPostTemplate = false; isCharImmediatelyPostPointerOrReference = false; - isInObjCMethodDefinition = false; isInObjCInterface = false; + isInObjCMethodDefinition = false; + isInObjCReturnType = false; isInObjCSelector = false; breakCurrentOneLineBlock = false; shouldRemoveNextClosingBracket = false; @@ -438,7 +435,7 @@ void ASFormatter::fixOptionVariableConflicts() */ string ASFormatter::nextLine() { - const string* newHeader; + const string* newHeader = NULL; bool isInVirginLine = isVirgin; isCharImmediatelyPostComment = false; isPreviousCharPostComment = false; @@ -556,7 +553,8 @@ string ASFormatter::nextLine() testForTimeToSplitFormattedLine(); continue; } - else if (currentChar == '"' || currentChar == '\'') + else if (currentChar == '"' + || (currentChar == '\'' && !isDigitSeparator(currentLine, charNum))) { formatQuoteOpener(); testForTimeToSplitFormattedLine(); @@ -609,8 +607,7 @@ string ASFormatter::nextLine() currentLine[charNum] = currentChar = ' '; shouldRemoveNextClosingBracket = false; assert(adjustChecksumIn(-'}')); - // if the line is empty, delete it - if (currentLine.find_first_not_of(" \t")) + if (isEmptyLine(currentLine)) continue; } @@ -893,6 +890,7 @@ string ASFormatter::nextLine() isCharImmediatelyPostNonInStmt = false; needHeaderOpeningBracket = false; shouldKeepLineUnbroken = false; + objCColonAlign = 0; isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); bracketTypeStack->push_back(newBracketType); @@ -1038,16 +1036,19 @@ string ASFormatter::nextLine() newHeader = findHeader(headers); // Qt headers may be variables in C++ - if (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH) + if (isCStyle() + && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) { if (currentLine.find_first_of("=;", charNum) != string::npos) newHeader = NULL; } + else if (newHeader == &AS_USING + && ASBeautifier::peekNextChar(currentLine, + charNum + (*newHeader).length() - 1) != '(') + newHeader = NULL; if (newHeader != NULL) { - const string* previousHeader; - // recognize closing headers of do..while, if..else, try..catch..finally if ((newHeader == &AS_ELSE && currentHeader == &AS_IF) || (newHeader == &AS_WHILE && currentHeader == &AS_DO) @@ -1061,7 +1062,7 @@ string ASFormatter::nextLine() || (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) foundClosingHeader = true; - previousHeader = currentHeader; + const string* previousHeader = currentHeader; currentHeader = newHeader; needHeaderOpeningBracket = true; @@ -1095,8 +1096,12 @@ string ASFormatter::nextLine() isNonParenHeader = findHeader(nonParenHeaders) != NULL; // join 'else if' statements - if (currentHeader == &AS_IF && previousHeader == &AS_ELSE && isInLineBreak - && !shouldBreakElseIfs && !isCharImmediatelyPostLineComment) + if (currentHeader == &AS_IF + && previousHeader == &AS_ELSE + && isInLineBreak + && !shouldBreakElseIfs + && !isCharImmediatelyPostLineComment + && !isImmediatelyPostPreprocessor) { // 'else' must be last thing on the line size_t start = formattedLine.length() >= 6 ? formattedLine.length() - 6 : 0; @@ -1192,9 +1197,7 @@ string ASFormatter::nextLine() else if ((newHeader = findHeader(preCommandHeaders)) != NULL) { // a 'const' variable is not a preCommandHeader - if (previousNonWSChar != ';' - && previousNonWSChar != '{' - && getPreviousWord(currentLine, charNum) != AS_STATIC) + if (previousNonWSChar == ')') foundPreCommandHeader = true; } else if ((newHeader = findHeader(castOperators)) != NULL) @@ -1430,21 +1433,17 @@ string ASFormatter::nextLine() continue; } else if ((currentChar == '-' || currentChar == '+') + && charNum == 0 && peekNextChar() == '(' && isBracketType(bracketTypeStack->back(), NULL_TYPE) && !isInPotentialCalculation) { isInObjCMethodDefinition = true; + isImmediatelyPostObjCMethodPrefix = true; isInObjCInterface = false; + if (getAlignMethodColon()) + objCColonAlign = findObjCColonAlignment(); appendCurrentChar(); - if (shouldPadMethodPrefix || shouldUnPadMethodPrefix) - { - size_t i = currentLine.find_first_not_of(" \t", charNum + 1); - if (i != string::npos) - goForward(i - charNum - 1); - if (shouldPadMethodPrefix) - appendSpaceAfter(); - } continue; } @@ -1513,9 +1512,22 @@ string ASFormatter::nextLine() continue; } + // remove spaces before commas + if (currentChar == ',') + { + const size_t len = formattedLine.length(); + size_t lastText = formattedLine.find_last_not_of(' '); + if (lastText != string::npos && lastText < len - 1) + { + formattedLine.resize(lastText + 1); + int size_diff = len - (lastText + 1); + spacePadNum -= size_diff; + } + } + // pad commas and semi-colons if (currentChar == ';' - || (currentChar == ',' && shouldPadOperators)) + || (currentChar == ',' && (shouldPadOperators || shouldPadCommas))) { char nextChar = ' '; if (charNum + 1 < (int) currentLine.length()) @@ -1536,16 +1548,38 @@ string ASFormatter::nextLine() } } - // do NOT use 'continue' after this, it must do padParens if necessary - if (currentChar == '(' - && shouldPadHeader - && (isCharImmediatelyPostReturn || isCharImmediatelyPostThrow)) - appendSpacePad(); - - if ((currentChar == '(' || currentChar == ')') - && (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen)) + // pad parens + if (currentChar == '(' || currentChar == ')') { - padParens(); + if (currentChar == '(') + { + if (shouldPadHeader + && (isCharImmediatelyPostReturn || isCharImmediatelyPostThrow)) + appendSpacePad(); + } + + if (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen) + padParens(); + else + appendCurrentChar(); + + if (currentChar == '(' + && isImmediatelyPostObjCMethodPrefix + && (shouldPadMethodPrefix || shouldUnPadMethodPrefix)) + padParenObjC(); + if (currentChar == ')' + && isInObjCReturnType + && (shouldPadReturnType || shouldUnPadReturnType)) + padParenObjC(); + + if (currentChar == '(' && isImmediatelyPostObjCMethodPrefix) + { + isImmediatelyPostObjCMethodPrefix = false; + isInObjCReturnType = true; + } + else if (currentChar == ')' && isInObjCReturnType) + isInObjCReturnType = false; + continue; } @@ -1593,6 +1627,7 @@ string ASFormatter::nextLine() isIndentableProprocessor = false; isElseHeaderIndent = elseHeaderFollowsComments; isCaseHeaderCommentIndent = caseHeaderFollowsComments; + objCColonAlignSubsequent = objCColonAlign; if (isCharImmediatelyPostNonInStmt) { isNonInStatementArray = false; @@ -1725,6 +1760,19 @@ void ASFormatter::setBreakElseIfsMode(bool state) shouldBreakElseIfs = state; } +/** +* set comma padding mode. +* options: +* true statement commas and semicolons will be padded with spaces around them. +* false statement commas and semicolons will not be padded. +* +* @param state the padding mode. +*/ +void ASFormatter::setCommaPaddingMode(bool state) +{ + shouldPadCommas = state; +} + /** * set maximum code length * @@ -1863,6 +1911,18 @@ void ASFormatter::setMethodPrefixUnPaddingMode(bool state) shouldUnPadMethodPrefix = state; } +// set objective-c '-' or '+' return type padding mode. +void ASFormatter::setReturnTypePaddingMode(bool state) +{ + shouldPadReturnType = state; +} + +// set objective-c '-' or '+' return type unpadding mode. +void ASFormatter::setReturnTypeUnPaddingMode(bool state) +{ + shouldUnPadReturnType = state; +} + /** * set objective-c method colon padding mode. * @@ -2194,85 +2254,82 @@ bool ASFormatter::getNextChar() */ bool ASFormatter::getNextLine(bool emptyLineWasDeleted /*false*/) { - if (sourceIterator->hasMoreLines()) - { - 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++; - if (endOfAsmReached) - endOfAsmReached = isInAsmBlock = isInAsm = false; - shouldKeepLineUnbroken = false; - isInCommentStartLine = false; - isInCase = false; - isInAsmOneLine = false; - isHeaderInMultiStatementLine = false; - isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; - haveLineContinuationChar = false; - isImmediatelyPostEmptyLine = lineIsEmpty; - 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) - isInLineBreak = true; - 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; - if (!isInComment - && (previousNonWSChar != '\\' - || isEmptyLine(currentLine))) - isInPreprocessor = false; - - if (passedSemicolon) - isInExecSQL = false; - initNewLine(); - - currentChar = currentLine[charNum]; - if (isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) - isInLineBreak = false; - isInHorstmannRunIn = false; - - if (currentChar == '\t' && shouldConvertTabs) - convertTabToSpaces(); - - // check for an empty line inside a command bracket. - // if yes then read the next line (calls getNextLine recursively). - // must be after initNewLine. - if (shouldDeleteEmptyLines - && lineIsEmpty - && isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 1], COMMAND_TYPE)) - { - if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) - { - isInPreprocessor = isImmediatelyPostPreprocessor; // restore - lineIsEmpty = false; - return getNextLine(true); - } - } - return true; - } - else + if (!sourceIterator->hasMoreLines()) { endOfCodeReached = true; return false; } + 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++; + if (endOfAsmReached) + endOfAsmReached = isInAsmBlock = isInAsm = false; + shouldKeepLineUnbroken = false; + isInCommentStartLine = false; + isInCase = false; + isInAsmOneLine = false; + isHeaderInMultiStatementLine = false; + isInQuoteContinuation = isInVerbatimQuote || haveLineContinuationChar; + haveLineContinuationChar = false; + isImmediatelyPostEmptyLine = lineIsEmpty; + 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) + isInLineBreak = true; + 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; + if (!isInComment + && (previousNonWSChar != '\\' + || isEmptyLine(currentLine))) + isInPreprocessor = false; + + if (passedSemicolon) + isInExecSQL = false; + initNewLine(); + + currentChar = currentLine[charNum]; + if (isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) + isInLineBreak = false; + isInHorstmannRunIn = false; + + if (currentChar == '\t' && shouldConvertTabs) + convertTabToSpaces(); + + // check for an empty line inside a command bracket. + // if yes then read the next line (calls getNextLine recursively). + // must be after initNewLine. + if (shouldDeleteEmptyLines + && lineIsEmpty + && isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 1], COMMAND_TYPE)) + { + if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) + { + isInPreprocessor = isImmediatelyPostPreprocessor; // restore + lineIsEmpty = false; + return getNextLine(true); + } + } + return true; } /** @@ -2427,7 +2484,7 @@ void ASFormatter::appendChar(char ch, bool canBreakLine) * @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(); @@ -2443,7 +2500,7 @@ void ASFormatter::appendSequence(const string &sequence, bool canBreakLine) * @param sequence the sequence to append. * @param canBreakLine if true, a registered line-break */ -void ASFormatter::appendOperator(const string &sequence, bool canBreakLine) +void ASFormatter::appendOperator(const string& sequence, bool canBreakLine) { if (canBreakLine && isInLineBreak) breakLine(); @@ -2546,7 +2603,7 @@ BracketType ASFormatter::getBracketType() { assert(currentChar == '{'); - BracketType returnVal; + BracketType returnVal = NULL_TYPE; if ((previousNonWSChar == '=' || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) @@ -2630,7 +2687,7 @@ BracketType ASFormatter::getBracketType() */ bool ASFormatter::isClassInitializer() const { - assert(currentLine[charNum] == ':'); + assert(currentChar == ':'); assert(previousChar != ':' && peekNextChar() != ':'); // not part of '::' // this should be similar to ASBeautifier::parseCurrentLine() @@ -2664,7 +2721,7 @@ bool ASFormatter::isClassInitializer() const * * @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; } @@ -2746,6 +2803,8 @@ bool ASFormatter::isPointerOrReference() const //check for rvalue reference if (currentChar == '&' && nextChar == '&') { + if (previousNonWSChar == '>') + return true; string followingText = peekNextText(currentLine.substr(charNum + 2)); if (followingText.length() > 0 && followingText[0] == ')') return true; @@ -2790,15 +2849,13 @@ bool ASFormatter::isPointerOrReference() const { if (followingOperator == &AS_ASSIGN || followingOperator == &AS_COLON) return true; - else - return false; + return false; } if (isBracketType(bracketTypeStack->back(), COMMAND_TYPE) || squareBracketCount > 0) return false; - else - return true; + return true; } // checks on operators in parens with following '(' @@ -2934,7 +2991,7 @@ bool ASFormatter::isDereferenceOrAddressOf() const */ bool ASFormatter::isPointerOrReferenceCentered() const { - assert(currentLine[charNum] == '*' || currentLine[charNum] == '&' || currentLine[charNum] == '^'); + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); int prNum = charNum; int lineLength = (int) currentLine.length(); @@ -2976,17 +3033,15 @@ bool ASFormatter::isPointerOrReferenceCentered() const * * @return whether word is a pointer or reference variable. */ -bool ASFormatter::isPointerOrReferenceVariable(string &word) const +bool ASFormatter::isPointerOrReferenceVariable(string& word) const { - if (word == "char" + return (word == "char" || word == "int" || word == "void" || (word.length() >= 6 // check end of word for _t && word.compare(word.length() - 2, 2, "_t") == 0) || word == "INT" - || word == "VOID") - return true; - return false; + || word == "VOID"); } /** @@ -3042,8 +3097,7 @@ bool ASFormatter::isInExponent() const return ((prevFormattedChar == 'e' || prevFormattedChar == 'E') && (prevPrevFormattedChar == '.' || isDigit(prevPrevFormattedChar))); } - else - return false; + return false; } /** @@ -3082,7 +3136,7 @@ bool ASFormatter::isNonInStatementArrayBracket() const * 1 = one-line bracket has been reached. * 2 = one-line bracket has been reached and is followed by a comma. */ -int ASFormatter::isOneLineBlockReached(string &line, int startChar) const +int ASFormatter::isOneLineBlockReached(string& line, int startChar) const { assert(line[startChar] == '{'); @@ -3121,7 +3175,8 @@ int ASFormatter::isOneLineBlockReached(string &line, int startChar) const continue; } - if (ch == '"' || ch == '\'') + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) { isInQuote_ = true; quoteChar_ = ch; @@ -3251,7 +3306,7 @@ bool ASFormatter::isUniformInitializerBracket() const * @param firstLine the first line to check * @return the next non-whitespace substring. */ -string ASFormatter::peekNextText(const string &firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const +string ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const { bool isFirstLine = true; bool needReset = shouldReset; @@ -3881,16 +3936,6 @@ void ASFormatter::formatPointerOrReferenceCast(void) } else appendSequence(sequenceToInsert, false); - // remove trailing whitespace if comma follows - char nextChar = peekNextChar(); - if (nextChar == ',') - { - while (isWhiteSpace(currentLine[charNum + 1])) - { - goForward(1); - spacePadNum--; - } - } } /** @@ -3901,8 +3946,8 @@ void ASFormatter::formatPointerOrReferenceCast(void) */ void ASFormatter::padParens(void) { - assert(shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen); assert(currentChar == '(' || currentChar == ')'); + assert(shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen); int spacesOutsideToDelete = 0; int spacesInsideToDelete = 0; @@ -4096,6 +4141,98 @@ void ASFormatter::padParens(void) return; } +/** +* add or remove space padding to objective-c parens +* these options have precedence over the padParens methods +* the padParens method has already been called, this method adjusts +*/ +void ASFormatter::padParenObjC(void) +{ + // the paren was previously been written to formattedLine + assert(formattedLine[0] == '+' || formattedLine[0] == '-'); + assert(formattedLine.find('(') != string::npos + || formattedLine.find(')') != string::npos); + assert(isImmediatelyPostObjCMethodPrefix || isInObjCReturnType); + assert(shouldPadMethodPrefix || shouldUnPadMethodPrefix + || shouldPadReturnType || shouldUnPadReturnType); + + if (isImmediatelyPostObjCMethodPrefix) + { + size_t prefix = formattedLine.find_first_of("+-"); + if (prefix == string::npos) + return; + size_t paren = formattedLine.find_first_of("("); + if (paren == string::npos) + return; + int spaces = paren - prefix - 1; + if (shouldPadMethodPrefix) + { + if (spaces == 0) + { + formattedLine.insert(prefix + 1, 1, ' '); + spacePadNum += 1; + } + else if (spaces > 1) + { + formattedLine.erase(prefix + 1, spaces - 1); + spacePadNum -= spaces - 1; + } + } + // this option will be ignored if used with pad-method-prefix + else if (shouldUnPadMethodPrefix) + { + if (spaces > 0) + { + formattedLine.erase(prefix + 1, spaces); + spacePadNum -= spaces; + } + } + } + + if (isInObjCReturnType) + { + size_t nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == string::npos) + return; + int spaces = nextText - charNum - 1; + if (shouldPadReturnType) + { + if (spaces == 0) + { + // this will already be padded if pad-paren is used + if (formattedLine[formattedLine.length() - 1] != ' ') + { + formattedLine.append(" "); + spacePadNum += 1; + } + } + else if (spaces > 1) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces - 1); + spacePadNum -= spaces - 1; + } + } + // this option will be ignored if used with pad-return-type + else if (shouldUnPadReturnType) + { + // this will already be padded if pad-paren is used + if (formattedLine[formattedLine.length() - 1] == ' ') + { + spacePadNum -= formattedLine.length() - 1 - nextText; + int lastText = formattedLine.find_last_not_of(" \t"); + formattedLine.resize(lastText + 1); + } + if (spaces > 0) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces); + spacePadNum -= spaces; + } + } + } +} + /** * format opening bracket as attached or broken * currentChar contains the bracket @@ -4588,8 +4725,7 @@ void ASFormatter::formatRunIn() indent.append(indentLength_, ' '); // replace spaces indents with tab indents size_t tabCount = indent.length() / tabLength_; // truncate extra spaces - indent.erase(0U, tabCount * tabLength_); - indent.insert(0U, tabCount, '\t'); + indent.replace(0U, tabCount * tabLength_, tabCount, '\t'); horstmannIndentChars = indentLength_; if (indent[0] == ' ') // allow for bracket indent.erase(0, 1); @@ -4658,7 +4794,7 @@ void ASFormatter::formatArrayRunIn() * delete a bracketTypeStack vector object * BracketTypeStack did not work with the DeleteContainer template */ -void ASFormatter::deleteContainer(vector* &container) +void ASFormatter::deleteContainer(vector*& container) { if (container != NULL) { @@ -4674,7 +4810,7 @@ void ASFormatter::deleteContainer(vector* &container) * used for all vectors except bracketTypeStack */ template -void ASFormatter::deleteContainer(T &container) +void ASFormatter::deleteContainer(T& container) { if (container != NULL) { @@ -4688,7 +4824,7 @@ void ASFormatter::deleteContainer(T &container) * initialize a BracketType vector object * BracketType did not work with the DeleteContainer template */ -void ASFormatter::initContainer(vector* &container, vector* value) +void ASFormatter::initContainer(vector*& container, vector* value) { if (container != NULL) deleteContainer(container); @@ -4701,7 +4837,7 @@ void ASFormatter::initContainer(vector* &container, vector -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 @@ -4720,7 +4856,7 @@ void ASFormatter::initContainer(T &container, T value) */ void ASFormatter::convertTabToSpaces() { - assert(currentLine[charNum] == '\t'); + assert(currentChar == '\t'); // do NOT replace if in quotes if (isInQuote || isInQuoteContinuation) @@ -4755,11 +4891,9 @@ bool ASFormatter::isOkToBreakBlock(BracketType bracketType) const */ bool ASFormatter::isSharpStyleWithParen(const string* header) const { - if (isSharpStyle() && peekNextChar() == '(' + return (isSharpStyle() && peekNextChar() == '(' && (header == &AS_CATCH - || header == &AS_DELEGATE)) - return true; - return false; + || header == &AS_DELEGATE)); } /** @@ -4767,7 +4901,7 @@ bool ASFormatter::isSharpStyleWithParen(const string* header) const * firstLine must contain the start of the comment. * return value is a pointer to the header or NULL. */ -const string* ASFormatter::checkForHeaderFollowingComment(const string &firstLine) const +const string* ASFormatter::checkForHeaderFollowingComment(const string& firstLine) const { assert(isInComment || isInLineComment); assert(shouldBreakElseIfs || shouldBreakBlocks || isInSwitchStatement()); @@ -4882,16 +5016,16 @@ bool ASFormatter::isCurrentBracketBroken() const { return false; } - else if (shouldAttachClass - && (isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE))) + if (shouldAttachClass + && (isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE))) { return false; } - else if (shouldAttachInline - && isCStyle() // for C++ only - && bracketFormatMode != RUN_IN_MODE - && isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) + if (shouldAttachInline + && isCStyle() // for C++ only + && bracketFormatMode != RUN_IN_MODE + && isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) { size_t i; for (i = 1; i < bracketTypeStack->size(); i++) @@ -5167,7 +5301,7 @@ void ASFormatter::formatLineCommentOpener() lineCommentNoIndent = true; } // move comment if spaces were added or deleted - if (lineCommentNoIndent == false && spacePadNum != 0 && !isInLineBreak) + if (!lineCommentNoIndent && spacePadNum != 0 && !isInLineBreak) adjustComments(); formattedLineCommentNum = formattedLine.length(); @@ -5293,11 +5427,8 @@ void ASFormatter::formatQuoteBody() goForward(1); return; } - else - { - isInQuote = false; - isInVerbatimQuote = false; - } + isInQuote = false; + isInVerbatimQuote = false; } } else if (quoteChar == currentChar) @@ -5328,7 +5459,8 @@ void ASFormatter::formatQuoteBody() */ void ASFormatter::formatQuoteOpener() { - assert(currentChar == '"' || currentChar == '\''); + assert(currentChar == '"' + || (currentChar == '\'' && !isDigitSeparator(currentLine, charNum))); isInQuote = true; quoteChar = currentChar; @@ -5422,7 +5554,7 @@ int ASFormatter::getCurrentLineCommentAdjustment() * * @return is the previous word or an empty string if none found. */ -string ASFormatter::getPreviousWord(const string &line, int currPos) const +string ASFormatter::getPreviousWord(const string& line, int currPos) const { // get the last legal word (may be a number) if (currPos == 0) @@ -5672,7 +5804,7 @@ bool ASFormatter::removeBracketsFromStatement() * @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*/) +size_t ASFormatter::findNextChar(string& line, char searchChar, int searchStart /*0*/) const { // find the next searchChar size_t i; @@ -5689,7 +5821,8 @@ size_t ASFormatter::findNextChar(string &line, char searchChar, int searchStart if (i >= line.length()) return string::npos; } - if (line[i] == '\'' || line[i] == '\"') + if (line[i] == '"' + || (line[i] == '\'' && !isDigitSeparator(line, i))) { char quote = line[i]; while (i < line.length()) @@ -5726,7 +5859,7 @@ size_t ASFormatter::findNextChar(string &line, char searchChar, int searchStart * @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()); @@ -5778,7 +5911,8 @@ bool ASFormatter::isStructAccessModified(string &firstLine, size_t index) const continue; } - if (nextLine_[i] == '"' || nextLine_[i] == '\'') + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) { isInQuote_ = true; quoteChar_ = nextLine_[i]; @@ -5829,7 +5963,7 @@ bool ASFormatter::isStructAccessModified(string &firstLine, size_t index) const * @param index the current line index. * @return true if the block is indentable. */ -bool ASFormatter::isIndentablePreprocessorBlock(string &firstLine, size_t index) +bool ASFormatter::isIndentablePreprocessorBlock(string& firstLine, size_t index) { assert(firstLine[index] == '#'); @@ -5839,6 +5973,8 @@ bool ASFormatter::isIndentablePreprocessorBlock(string &firstLine, size_t index) bool blockContainsBrackets = false; bool blockContainsDefineContinuation = false; bool isInClassConstructor = false; + bool isPotentialHeaderGuard = false; // ifndef is first preproc statement + bool isPotentialHeaderGuard2 = false; // define is within the first proproc int numBlockIndents = 0; int lineParenCount = 0; string nextLine_ = firstLine.substr(index); @@ -5884,7 +6020,8 @@ bool ASFormatter::isIndentablePreprocessorBlock(string &firstLine, size_t index) continue; } - if (nextLine_[i] == '"' || nextLine_[i] == '\'') + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) { isInQuote_ = true; quoteChar_ = nextLine_[i]; @@ -5908,6 +6045,8 @@ bool ASFormatter::isIndentablePreprocessorBlock(string &firstLine, size_t index) { processedFirstConditional = true; isFirstPreprocConditional = true; + if (isNDefPreprocStatement(nextLine_, preproc)) + isPotentialHeaderGuard = true; } } else if (preproc == "endif") @@ -5918,9 +6057,13 @@ bool ASFormatter::isIndentablePreprocessorBlock(string &firstLine, size_t index) if (numBlockIndents == 0) goto EndOfWhileLoop; } - else if (preproc == "define" && nextLine_[nextLine_.length() - 1] == '\\') + else if (preproc == "define") { - blockContainsDefineContinuation = true; + if (nextLine_[nextLine_.length() - 1] == '\\') + blockContainsDefineContinuation = true; + // check for potential header include guards + else if (isPotentialHeaderGuard && numBlockIndents == 1) + isPotentialHeaderGuard2 = true; } i = nextLine_.length(); continue; @@ -5960,11 +6103,11 @@ EndOfWhileLoop: // find next executable instruction // this WILL RESET the get pointer string nextText = peekNextText("", false, needReset); - // bypass header include guards, with an exception for small test files + // bypass header include guards if (isFirstPreprocConditional) { isFirstPreprocConditional = false; - if (nextText.empty() && sourceIterator->getStreamLength() > 250) + if (nextText.empty() && isPotentialHeaderGuard2) { isInIndentableBlock = false; preprocBlockEnd = 0; @@ -5977,6 +6120,23 @@ EndOfWhileLoop: return isInIndentableBlock; } +bool ASFormatter::isNDefPreprocStatement(string& nextLine_, string& preproc) const +{ + if (preproc == "ifndef") + return true; + // check for '!defined' + if (preproc == "if") + { + size_t i = nextLine_.find("!"); + if (i == string::npos) + return false; + i = nextLine_.find_first_not_of(" \t", ++i); + if (i != string::npos && nextLine_.compare(i, 7, "defined") == 0) + return true; + } + return false; +} + /** * Check to see if this is an EXEC SQL statement. * @@ -5984,7 +6144,7 @@ EndOfWhileLoop: * @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; @@ -6174,7 +6334,8 @@ void ASFormatter::checkIfTemplateOpener() continue; } - if (currentChar_ == '"' || currentChar_ == '\'') + if (currentChar_ == '"' + || (currentChar_ == '\'' && !isDigitSeparator(nextLine_, i))) { isInQuote_ = true; quoteChar_ = currentChar_; @@ -6364,7 +6525,7 @@ void ASFormatter::updateFormattedLineSplitPoints(char appendedChar) } } -void ASFormatter::updateFormattedLineSplitPointsOperator(const string &sequence) +void ASFormatter::updateFormattedLineSplitPointsOperator(const string& sequence) { assert(maxCodeLength != string::npos); assert(formattedLine.length() > 0); @@ -6498,7 +6659,7 @@ bool ASFormatter::isOkToSplitFormattedLine() clearFormattedLineSplitPoints(); return false; } - else if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) + if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) { shouldKeepLineUnbroken = true; if (!isBracketType(bracketTypeStack->back(), ARRAY_NIS_TYPE)) @@ -6684,7 +6845,7 @@ bool ASFormatter::pointerSymbolFollows() const * Compute the input checksum. * This is called as an assert so it for is debug config only */ -bool ASFormatter::computeChecksumIn(const string ¤tLine_) +bool ASFormatter::computeChecksumIn(const string& currentLine_) { for (size_t i = 0; i < currentLine_.length(); i++) if (!isWhiteSpace(currentLine_[i])) @@ -6716,7 +6877,7 @@ size_t ASFormatter::getChecksumIn() const * Compute the output checksum. * This is called as an assert so it is for debug config only */ -bool ASFormatter::computeChecksumOut(const string &beautifiedLine) +bool ASFormatter::computeChecksumOut(const string& beautifiedLine) { for (size_t i = 0; i < beautifiedLine.length(); i++) if (!isWhiteSpace(beautifiedLine[i])) @@ -6845,10 +7006,114 @@ void ASFormatter::resetEndOfStatement() questionMarkStack->pop_back(); } +// Find the colon alignment for an Objective-C method definition. +int ASFormatter::findObjCColonAlignment() const +{ + assert(currentChar == '+' || currentChar == '-'); + assert(getAlignMethodColon()); + + bool isFirstLine = true; + bool haveFirstColon = false; + bool needReset = false; + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + int colonAdjust = 0; + int colonAlign = 0; + string nextLine_ = currentLine; + + // peek next line + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (!isFirstLine) + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + haveFirstColon = false; + nextLine_ = ASBeautifier::trim(nextLine_); + for (size_t i = 0; i < nextLine_.length(); i++) + { + if (isWhiteSpace(nextLine_[i])) + continue; + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (nextLine_.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (nextLine_[i] == '\\') + { + ++i; + continue; + } + if (isInQuote_) + { + if (nextLine_[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) + { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) + { + i = nextLine_.length(); + continue; + } + // process the current char + if (nextLine_[i] == '{' || nextLine_[i] == ';') + goto EndOfWhileLoop; + if (isFirstLine) // colon align does not include the first line + continue; + if (haveFirstColon) + continue; + // compute colon adjustment + if (nextLine_[i] == ':') + { + haveFirstColon = true; + if (shouldPadMethodColon) + { + int spacesStart; + for (spacesStart = i; spacesStart > 0; spacesStart--) + if (!isWhiteSpace(nextLine_[spacesStart - 1])) + break; + int spaces = i - spacesStart; + if (objCColonPadMode == COLON_PAD_ALL || objCColonPadMode == COLON_PAD_BEFORE) + colonAdjust = 1 - spaces; + else if (objCColonPadMode == COLON_PAD_NONE || objCColonPadMode == COLON_PAD_AFTER) + colonAdjust = 0 - spaces; + } + // compute alignment + int colonPosition = i + colonAdjust; + if (colonPosition > colonAlign) + colonAlign = colonPosition; + } + } // end of for loop + isFirstLine = false; + } // end of while loop +EndOfWhileLoop: + if (needReset) + sourceIterator->peekReset(); + return colonAlign; +} + // pad an Objective-C method colon void ASFormatter::padObjCMethodColon() { assert(currentChar == ':'); + int commentAdjust = 0; char nextChar = peekNextChar(); if (objCColonPadMode == COLON_PAD_NONE || objCColonPadMode == COLON_PAD_AFTER @@ -6856,14 +7121,20 @@ void ASFormatter::padObjCMethodColon() { // remove spaces before for (int i = formattedLine.length() - 1; (i > -1) && isWhiteSpace(formattedLine[i]); i--) + { formattedLine.erase(i); + --commentAdjust; + } } else { // pad space before for (int i = formattedLine.length() - 1; (i > 0) && isWhiteSpace(formattedLine[i]); i--) if (isWhiteSpace(formattedLine[i - 1])) + { formattedLine.erase(i); + --commentAdjust; + } appendSpacePad(); } if (objCColonPadMode == COLON_PAD_NONE @@ -6871,21 +7142,37 @@ void ASFormatter::padObjCMethodColon() || nextChar == ')') { // remove spaces after - // do not need to bump i since a char is erased - size_t i = charNum + 1; - while ((i < currentLine.length()) && isWhiteSpace(currentLine[i])) - currentLine.erase(i, 1); + int nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == (int)string::npos) + nextText = currentLine.length(); + int spaces = nextText - charNum - 1; + if (spaces > 0) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces); + spacePadNum -= spaces; + } } else { // pad space after - // do not need to bump i since a char is erased - size_t i = charNum + 1; - while ((i + 1 < currentLine.length()) && isWhiteSpace(currentLine[i])) - currentLine.erase(i, 1); - if (((int) currentLine.length() > charNum + 1) && !isWhiteSpace(currentLine[charNum + 1])) - currentLine.insert(charNum + 1, " "); + int nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == (int)string::npos) + nextText = currentLine.length(); + int spaces = nextText - charNum - 1; + if (spaces == 0) + { + currentLine.insert(charNum + 1, 1, ' '); + spacePadNum += 1; + } + else if (spaces > 1) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces - 1); + spacePadNum -= spaces - 1; + } } + spacePadNum += commentAdjust; } // Remove the leading '*' from a comment line and indent to the next tab. diff --git a/src/ASLocalizer.cpp b/src/ASLocalizer.cpp index 25e4983..3001522 100644 --- a/src/ASLocalizer.cpp +++ b/src/ASLocalizer.cpp @@ -1,38 +1,34 @@ +// ASLocalizer.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. // -// FILE ENCODING IS UTF-8 WITHOUT A BOM. -// русский 中文(简体) 日本 한국의 +// File encoding for this file is UTF-8 WITHOUT a byte order mark(BOM). +// русский 中文(简体) 日本語 한국의 +// +// Windows: +// Add the required "Language" to the system. +// The settings do NOT need to be changed to the added language. +// Change the "Region" settings. +// Change both the "Format" and the "Current Language..." settings. +// A restart is required if the codepage has changed. +// Windows problems: +// Hindi -no available locale, language pack removed +// Japanese - language pack install error +// Ukranian - displays a ? instead of i +// +// Linux: +// Change the LANG environment variable: LANG=fr_FR.UTF-8. +// setlocale() will use the LANG environment variable on Linux. // /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASLocalizer.cpp * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * - * To add a new language: + * To add a new language to this source module: * * Add a new translation class to ASLocalizer.h. - * Add the Add the English-Translation pair to the constructor in ASLocalizer.cpp. - * Update the WinLangCode array, if necessary. - * Add the language code to the function setTranslationClass(). + * Update the WinLangCode array in ASLocalizer.cpp. + * Add the language code to setTranslationClass() in ASLocalizer.cpp. + * Add the English-Translation pair to the constructor in ASLocalizer.cpp. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ @@ -48,7 +44,6 @@ #endif #ifdef __DMC__ - #include // digital mars doesn't have these const size_t SUBLANG_CHINESE_MACAU = 5; const size_t LANG_HINDI = 57; @@ -63,12 +58,12 @@ #include #include +#include // needed by some compilers #include #include #ifdef _MSC_VER #pragma warning(disable: 4996) // secure version deprecation warnings - // #pragma warning(disable: 4267) // 64 bit signed/unsigned loss of data #endif #ifdef __BORLANDC__ @@ -80,6 +75,10 @@ #pragma warning(disable: 981) // operands are evaluated in unspecified order #endif +#ifdef __clang__ + #pragma clang diagnostic ignored "-Wdeprecated-declarations" // wcstombs +#endif + namespace astyle { #ifndef ASTYLE_LIB @@ -100,10 +99,6 @@ ASLocalizer::ASLocalizer() m_translation = NULL; // Not all compilers support the C++ function locale::global(locale("")); - // For testing on Windows change the "Region and Language" settings or use AppLocale. - // For testing on Linux change the LANG environment variable: LANG=fr_FR.UTF-8. - // setlocale() will use the LANG environment variable on Linux. - char* localeName = setlocale(LC_ALL, ""); if (localeName == NULL) // use the english (ascii) defaults { @@ -139,22 +134,28 @@ static WinLangCode wlc[] = // sublanguage identifier http://msdn.microsoft.com/en-us/library/aa913256.aspx // language ID http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx { - { LANG_CHINESE, "zh" }, - { LANG_DUTCH, "nl" }, - { LANG_ENGLISH, "en" }, - { LANG_FINNISH, "fi" }, - { LANG_FRENCH, "fr" }, - { LANG_GERMAN, "de" }, - { LANG_HINDI, "hi" }, - { LANG_ITALIAN, "it" }, - { LANG_JAPANESE, "ja" }, - { LANG_KOREAN, "ko" }, - { LANG_POLISH, "pl" }, - { LANG_PORTUGUESE, "pt" }, - { LANG_RUSSIAN, "ru" }, - { LANG_SPANISH, "es" }, - { LANG_SWEDISH, "sv" }, - { LANG_UKRAINIAN, "uk" }, + { LANG_BULGARIAN, "bg" }, // bg-BG 1251 + { LANG_CHINESE, "zh" }, // zh-CHS, zh-CHT + { LANG_DUTCH, "nl" }, // nl-NL 1252 + { LANG_ENGLISH, "en" }, // en-US 1252 + { LANG_ESTONIAN, "et" }, // et-EE + { LANG_FINNISH, "fi" }, // fi-FI 1252 + { LANG_FRENCH, "fr" }, // fr-FR 1252 + { LANG_GERMAN, "de" }, // de-DE 1252 + { LANG_GREEK, "el" }, // el-GR 1253 + { LANG_HINDI, "hi" }, // hi-IN + { LANG_HUNGARIAN, "hu" }, // hu-HU 1250 + { LANG_ITALIAN, "it" }, // it-IT 1252 + { LANG_JAPANESE, "ja" }, // ja-JP + { LANG_KOREAN, "ko" }, // ko-KR + { LANG_NORWEGIAN, "nn" }, // nn-NO 1252 + { LANG_POLISH, "pl" }, // pl-PL 1250 + { LANG_PORTUGUESE, "pt" }, // pt-PT 1252 + { LANG_ROMANIAN, "ro" }, // ro-RO 1250 + { LANG_RUSSIAN, "ru" }, // ru-RU 1251 + { LANG_SPANISH, "es" }, // es-ES 1252 + { LANG_SWEDISH, "sv" }, // sv-SE 1252 + { LANG_UKRAINIAN, "uk" }, // uk-UA 1251 }; void ASLocalizer::setLanguageFromLCID(size_t lcid) @@ -224,16 +225,14 @@ void ASLocalizer::setLanguageFromName(const char* langID) // de_DE.iso88591@euro { // the constants describing the format of lang_LANG locale string - static const size_t LEN_LANG = 2; - m_lcid = 0; string langStr = langID; - m_langID = langStr.substr(0, LEN_LANG); + m_langID = langStr.substr(0, 2); // need the sublang for chinese - if (m_langID == "zh" && langStr[LEN_LANG] == '_') + if (m_langID == "zh" && langStr[2] == '_') { - string subLang = langStr.substr(LEN_LANG + 1, LEN_LANG); + string subLang = langStr.substr(3, 2); if (subLang == "CN" || subLang == "SG") m_subLangID = "CHS"; else @@ -262,7 +261,9 @@ void ASLocalizer::setTranslationClass() delete m_translation; m_translation = NULL; } - if (m_langID == "zh" && m_subLangID == "CHS") + if (m_langID == "bg") + m_translation = new Bulgarian; + else if (m_langID == "zh" && m_subLangID == "CHS") m_translation = new ChineseSimplified; else if (m_langID == "zh" && m_subLangID == "CHT") m_translation = new ChineseTraditional; @@ -270,24 +271,34 @@ void ASLocalizer::setTranslationClass() m_translation = new Dutch; else if (m_langID == "en") m_translation = new English; + else if (m_langID == "et") + m_translation = new Estonian; else if (m_langID == "fi") m_translation = new Finnish; else if (m_langID == "fr") m_translation = new French; else if (m_langID == "de") m_translation = new German; + else if (m_langID == "el") + m_translation = new Greek; else if (m_langID == "hi") m_translation = new Hindi; + else if (m_langID == "hu") + m_translation = new Hungarian; else if (m_langID == "it") m_translation = new Italian; else if (m_langID == "ja") m_translation = new Japanese; else if (m_langID == "ko") m_translation = new Korean; + else if (m_langID == "nn") + m_translation = new Norwegian; else if (m_langID == "pl") m_translation = new Polish; else if (m_langID == "pt") m_translation = new Portuguese; + else if (m_langID == "ro") + m_translation = new Romanian; else if (m_langID == "ru") m_translation = new Russian; else if (m_langID == "es") @@ -304,14 +315,14 @@ void ASLocalizer::setTranslationClass() // Translation base class methods. //---------------------------------------------------------------------------- -void Translation::addPair(const string &english, const wstring &translated) +void Translation::addPair(const string& english, const wstring& translated) // Add a string pair to the translation vector. { pair entry(english, translated); m_translation.push_back(entry); } -string Translation::convertToMultiByte(const wstring &wideStr) const +string Translation::convertToMultiByte(const wstring& wideStr) const // Convert wchar_t to a multibyte string using the currently assigned locale. // Return an empty string if an error occurs. { @@ -351,7 +362,7 @@ size_t Translation::getTranslationVectorSize() const return m_translation.size(); } -bool Translation::getWideTranslation(const string &stringIn, wstring &wideOut) const +bool Translation::getWideTranslation(const string& stringIn, wstring& wideOut) const // Get the wide translation string. Used for testing. { for (size_t i = 0; i < m_translation.size(); i++) @@ -367,25 +378,24 @@ bool Translation::getWideTranslation(const string &stringIn, wstring &wideOut) c return false; } -string &Translation::translate(const string &stringIn) const +string& Translation::translate(const string& stringIn) const // Translate a string. -// Return a static string instead of a member variable so the method can have a "const" designation. +// Return a mutable string so the method can have a "const" designation. // This allows "settext" to be called from a "const" method. { - static string mbTranslation; - mbTranslation.clear(); + m_mbTranslation.clear(); for (size_t i = 0; i < m_translation.size(); i++) { if (m_translation[i].first == stringIn) { - mbTranslation = convertToMultiByte(m_translation[i].second); + m_mbTranslation = convertToMultiByte(m_translation[i].second); break; } } // not found, return english - if (mbTranslation.empty()) - mbTranslation = stringIn; - return mbTranslation; + if (m_mbTranslation.empty()) + m_mbTranslation = stringIn; + return m_mbTranslation; } //---------------------------------------------------------------------------- @@ -393,13 +403,45 @@ string &Translation::translate(const string &stringIn) const // These classes have only a constructor which builds the language vector. //---------------------------------------------------------------------------- +Bulgarian::Bulgarian() // български +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Форматиран %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Непроменен %s\n"); // should align with formatted + addPair("Directory %s\n", L"директория %s\n"); + addPair("Exclude %s\n", L"Изключвам %s\n"); + addPair("Exclude (unmatched) %s\n", L"Изключване (несравнимо) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s форматиран %s hепроменен "); + addPair(" seconds ", L" секунди "); + addPair("%d min %d sec ", L"%d мин %d сек "); + addPair("%s lines\n", L"%s линии\n"); + addPair("Using default options file %s\n", L"Използване на файла възможности по подразбиране %s\n"); + addPair("Opening HTML documentation %s\n", L"Откриване HTML документация %s\n"); + addPair("Invalid option file options:", L"Невалидни опции опция файлове:"); + addPair("Invalid command line options:", L"Невалидни опции за командния ред:"); + addPair("For help on options type 'astyle -h'", L"За помощ относно възможностите тип 'astyle -h'"); + addPair("Cannot open options file", L"Не може да се отвори файл опции"); + addPair("Cannot open directory", L"Не може да се отвори директория"); + addPair("Cannot open HTML file %s\n", L"Не може да се отвори HTML файл %s\n"); + addPair("Command execute failure", L"Command изпълни недостатъчност"); + addPair("Command is not installed", L"Command не е инсталиран"); + addPair("Missing filename in %s\n", L"Липсва името на файла в %s\n"); + addPair("Recursive option with no wildcard", L"Рекурсивно опция, без маска"); + addPair("Did you intend quote the filename", L"Знаете ли намерение да цитирам името на файла"); + addPair("No file to process %s\n", L"Не файл за обработка %s\n"); + addPair("Did you intend to use --recursive", L"Знаете ли възнамерявате да използвате --recursive"); + addPair("Cannot process UTF-32 encoding", L"Не може да са UTF-32 кодиране"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style е прекратено"); +} + ChineseSimplified::ChineseSimplified() // 中文(简体) +// build the translation vector in the Translation base class { addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"未改变 %s\n"); // should align with formatted addPair("Directory %s\n", L"目录 %s\n"); addPair("Exclude %s\n", L"排除 %s\n"); - addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); + addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改变 "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); @@ -424,13 +466,14 @@ ChineseSimplified::ChineseSimplified() // 中文(简体) } ChineseTraditional::ChineseTraditional() // 中文(繁體) +// build the translation vector in the Translation base class { addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"未改變 %s\n"); // should align with formatted addPair("Directory %s\n", L"目錄 %s\n"); addPair("Exclude %s\n", L"排除 %s\n"); - addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); + addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); addPair("%s lines\n", L"%s 行\n"); @@ -488,6 +531,37 @@ English::English() // this class is NOT translated {} +Estonian::Estonian() // Eesti +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formaadis %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Muutumatu %s\n"); // should align with formatted + addPair("Directory %s\n", L"Kataloog %s\n"); + addPair("Exclude %s\n", L"Välista %s\n"); + addPair("Exclude (unmatched) %s\n", L"Välista (tasakaalustamata) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formaadis %s muutumatu "); + addPair(" seconds ", L" sekundit "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s read\n"); + addPair("Using default options file %s\n", L"Kasutades selliseid vaikimisi valikuid faili %s\n"); + addPair("Opening HTML documentation %s\n", L"Avamine HTML dokumentatsioon %s\n"); + addPair("Invalid option file options:", L"Vale valik faili võimalusi:"); + addPair("Invalid command line options:", L"Vale käsureavõtmetega:"); + addPair("For help on options type 'astyle -h'", L"Abiks võimaluste tüüp 'astyle -h'"); + addPair("Cannot open options file", L"Ei saa avada võimalusi faili"); + addPair("Cannot open directory", L"Ei saa avada kataloogi"); + addPair("Cannot open HTML file %s\n", L"Ei saa avada HTML-faili %s\n"); + addPair("Command execute failure", L"Käsk täita rike"); + addPair("Command is not installed", L"Käsk ei ole paigaldatud"); + addPair("Missing filename in %s\n", L"Kadunud failinimi %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiivne võimalus ilma metamärgi"); + addPair("Did you intend quote the filename", L"Kas te kavatsete tsiteerida failinimi"); + addPair("No file to process %s\n", L"No faili töötlema %s\n"); + addPair("Did you intend to use --recursive", L"Kas te kavatsete kasutada --recursive"); + addPair("Cannot process UTF-32 encoding", L"Ei saa töödelda UTF-32 kodeeringus"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style on lõpetatud"); +} + Finnish::Finnish() // Suomeksi // build the translation vector in the Translation base class { @@ -581,6 +655,37 @@ German::German() // Deutsch addPair("\nArtistic Style has terminated", L"\nArtistic Style ist beendet"); } +Greek::Greek() // ελληνικά +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Διαμορφωμένη %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Αμετάβλητος %s\n"); // should align with formatted + addPair("Directory %s\n", L"Κατάλογος %s\n"); + addPair("Exclude %s\n", L"Αποκλείω %s\n"); + addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s σχηματοποιημένη %s αμετάβλητες "); + addPair(" seconds ", L" δευτερόλεπτα "); + addPair("%d min %d sec ", L"%d λεπ %d δευ "); + addPair("%s lines\n", L"%s γραμμές\n"); + addPair("Using default options file %s\n", L"Χρησιμοποιώντας το αρχείο προεπιλεγμένες επιλογές %s\n"); + addPair("Opening HTML documentation %s\n", L"Εγκαίνια έγγραφα HTML %s\n"); + addPair("Invalid option file options:", L"Μη έγκυρες επιλογές αρχείου επιλογή:"); + addPair("Invalid command line options:", L"Μη έγκυρη επιλογές γραμμής εντολών:"); + addPair("For help on options type 'astyle -h'", L"Για βοήθεια σχετικά με το είδος επιλογές 'astyle -h'"); + addPair("Cannot open options file", L"Δεν μπορείτε να ανοίξετε το αρχείο επιλογών"); + addPair("Cannot open directory", L"Δεν μπορείτε να ανοίξετε τον κατάλογο"); + addPair("Cannot open HTML file %s\n", L"Δεν μπορείτε να ανοίξετε το αρχείο HTML %s\n"); + addPair("Command execute failure", L"Εντολή να εκτελέσει την αποτυχία"); + addPair("Command is not installed", L"Η εντολή δεν έχει εγκατασταθεί"); + addPair("Missing filename in %s\n", L"Λείπει το όνομα αρχείου σε %s\n"); + addPair("Recursive option with no wildcard", L"Αναδρομικές επιλογή χωρίς μπαλαντέρ"); + addPair("Did you intend quote the filename", L"Μήπως σκοπεύετε να αναφέρετε το όνομα του αρχείου"); + addPair("No file to process %s\n", L"Δεν υπάρχει αρχείο για την επεξεργασία %s\n"); + addPair("Did you intend to use --recursive", L"Μήπως σκοπεύετε να χρησιμοποιήσετε --recursive"); + addPair("Cannot process UTF-32 encoding", L"δεν μπορεί να επεξεργαστεί UTF-32 κωδικοποίηση"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style έχει λήξει"); +} + Hindi::Hindi() // हिन्दी // build the translation vector in the Translation base class { @@ -614,6 +719,37 @@ Hindi::Hindi() // हिन्दी addPair("\nArtistic Style has terminated", L"\nArtistic Style समाप्त किया है"); } +Hungarian::Hungarian() // Magyar +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formázott %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Változatlan %s\n"); // should align with formatted + addPair("Directory %s\n", L"Címjegyzék %s\n"); + addPair("Exclude %s\n", L"Kizár %s\n"); + addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formázott %s változatlan "); + addPair(" seconds ", L" másodperc "); + addPair("%d min %d sec ", L"%d jeg %d más "); + addPair("%s lines\n", L"%s vonalak\n"); + addPair("Using default options file %s\n", L"Az alapértelmezett beállítások fájl %s\n"); + addPair("Opening HTML documentation %s\n", L"Nyitó HTML dokumentáció %s\n"); + addPair("Invalid option file options:", L"Érvénytelen opció fájlbeállítást:"); + addPair("Invalid command line options:", L"Érvénytelen parancssori opciók:"); + addPair("For help on options type 'astyle -h'", L"Ha segítségre van lehetőség típus 'astyle-h'"); + addPair("Cannot open options file", L"Nem lehet megnyitni beállítási fájlban"); + addPair("Cannot open directory", L"Nem lehet megnyitni könyvtár"); + addPair("Cannot open HTML file %s\n", L"Nem lehet megnyitni a HTML fájlt %s\n"); + addPair("Command execute failure", L"Command végre hiba"); + addPair("Command is not installed", L"Parancs nincs telepítve"); + addPair("Missing filename in %s\n", L"Hiányzó fájlnév %s\n"); + addPair("Recursive option with no wildcard", L"Rekurzív kapcsolót nem wildcard"); + addPair("Did you intend quote the filename", L"Esetleg kívánja idézni a fájlnév"); + addPair("No file to process %s\n", L"Nincs fájl feldolgozása %s\n"); + addPair("Did you intend to use --recursive", L"Esetleg a használni kívánt --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nem tudja feldolgozni UTF-32 kódolással"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style megszűnt"); +} + Italian::Italian() // Italiano // build the translation vector in the Translation base class { @@ -645,43 +781,45 @@ Italian::Italian() // Italiano addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminato"); } -Japanese::Japanese() // 日本 +Japanese::Japanese() // 日本語 +// build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"フォーマット %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"変更 %s\n"); // should align with formatted + addPair("Formatted %s\n", L"フォーマット済みの %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"変わりません %s\n"); // should align with formatted addPair("Directory %s\n", L"ディレクトリ %s\n"); addPair("Exclude %s\n", L"除外する %s\n"); - addPair("Exclude (unmatched) %s\n", L"除外(マッチせず) %s\n"); - addPair(" %s formatted %s unchanged ", L" %sフォーマット %s 変更 "); + addPair("Exclude (unmatched) %s\n", L"除外する(一致しません) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s フフォーマット済みの %s 変わりません "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); - addPair("%s lines\n", L"%s の行\n"); - addPair("Using default options file %s\n", L"デフォルトの設定ファイルを使用してください %s\n"); - addPair("Opening HTML documentation %s\n", L"HTML文書を開く %s\n"); - addPair("Invalid option file options:", L"無効なコンフィギュレーションファイルオプション:"); + addPair("%s lines\n", L"%s ライン\n"); + addPair("Using default options file %s\n", L"デフォルトのオプションファイルを使用して、 %s\n"); + addPair("Opening HTML documentation %s\n", L"オープニングHTMLドキュメント %s\n"); + addPair("Invalid option file options:", L"無効なオプションファイルのオプション:"); addPair("Invalid command line options:", L"無効なコマンドラインオプション:"); - addPair("For help on options type 'astyle -h'", L"コマンドラインについてのヘルプは'astyle- h'を入力してください"); - addPair("Cannot open options file", L"コンフィギュレーションファイルを開くことができません"); - addPair("Cannot open directory", L"ディレクトリのオープンに失敗しました"); + addPair("For help on options type 'astyle -h'", L"コオプションの種類のヘルプについて'astyle- h'を入力してください"); + addPair("Cannot open options file", L"オプションファイルを開くことができません"); + addPair("Cannot open directory", L"ディレクトリを開くことができません。"); addPair("Cannot open HTML file %s\n", L"HTMLファイルを開くことができません %s\n"); - addPair("Command execute failure", L"コマンドの失敗を実行"); + addPair("Command execute failure", L"コマンドが失敗を実行します"); addPair("Command is not installed", L"コマンドがインストールされていません"); - addPair("Missing filename in %s\n", L"%s はファイル名で欠落しています\n"); - addPair("Recursive option with no wildcard", L"再帰的なオプションではワイルドカードではない"); - addPair("Did you intend quote the filename", L"あなたは、ファイル名を参照するつもり"); - addPair("No file to process %s\n", L"いいえファイルは処理できません %s\n"); - addPair("Did you intend to use --recursive", L"あなたが使用する予定 --recursive"); - addPair("Cannot process UTF-32 encoding", L"UTF- 32エンコーディングを処理できない"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 実行が終了しました"); + addPair("Missing filename in %s\n", L"%s で、ファイル名がありません\n"); + addPair("Recursive option with no wildcard", L"無ワイルドカードを使用して再帰的なオプション"); + addPair("Did you intend quote the filename", L"あなたはファイル名を引用するつもりでした"); + addPair("No file to process %s\n", L"いいえファイルは処理しないように %s\n"); + addPair("Did you intend to use --recursive", L"あなたは--recursive使用するつもりでした"); + addPair("Cannot process UTF-32 encoding", L"UTF - 32エンコーディングを処理できません"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 終了しました"); } Korean::Korean() // 한국의 +// build the translation vector in the Translation base class { addPair("Formatted %s\n", L"수정됨 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"변경없음 %s\n"); // should align with formatted addPair("Directory %s\n", L"디렉토리 %s\n"); - addPair("Exclude %s\n", L"제외됨 %s\n"); - addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); + addPair("Exclude %s\n", L"제외됨 %s\n"); + addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); addPair(" %s formatted %s unchanged ", L" %s 수정됨 %s 변경없음 "); addPair(" seconds ", L" 초 "); addPair("%d min %d sec ", L"%d 분 %d 초 "); @@ -705,6 +843,37 @@ Korean::Korean() // 한국의 addPair("\nArtistic Style has terminated", L"\nArtistic Style를 종료합니다"); } +Norwegian::Norwegian() // Norsk +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formatert %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Uendret %s\n"); // should align with formatted + addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Exclude %s\n", L"Ekskluder %s\n"); + addPair("Exclude (unmatched) %s\n", L"Ekskluder (uovertruffen) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatert %s uendret "); + addPair(" seconds ", L" sekunder "); + addPair("%d min %d sec ", L"%d min %d sek? "); + addPair("%s lines\n", L"%s linjer\n"); + addPair("Using default options file %s\n", L"Ved hjelp av standardalternativer fil %s\n"); + addPair("Opening HTML documentation %s\n", L"Åpning HTML dokumentasjon %s\n"); + addPair("Invalid option file options:", L"Ugyldige alternativ filalternativer:"); + addPair("Invalid command line options:", L"Kommandolinjevalg Ugyldige:"); + addPair("For help on options type 'astyle -h'", L"For hjelp til alternativer type 'astyle -h'"); + addPair("Cannot open options file", L"Kan ikke åpne alternativer fil"); + addPair("Cannot open directory", L"Kan ikke åpne katalog"); + addPair("Cannot open HTML file %s\n", L"Kan ikke åpne HTML-fil %s\n"); + addPair("Command execute failure", L"Command utføre svikt"); + addPair("Command is not installed", L"Command er ikke installert"); + addPair("Missing filename in %s\n", L"Mangler filnavn i %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiv alternativ uten wildcard"); + addPair("Did you intend quote the filename", L"Har du tenkt sitere filnavnet"); + addPair("No file to process %s\n", L"Ingen fil å behandle %s\n"); + addPair("Did you intend to use --recursive", L"Har du tenkt å bruke --recursive"); + addPair("Cannot process UTF-32 encoding", L"Kan ikke behandle UTF-32 koding"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style har avsluttet"); +} + Polish::Polish() // Polski // build the translation vector in the Translation base class { @@ -767,6 +936,37 @@ Portuguese::Portuguese() // Português addPair("\nArtistic Style has terminated", L"\nArtistic Style terminou"); } +Romanian::Romanian() // Română +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formatat %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Neschimbat %s\n"); // should align with formatted + addPair("Directory %s\n", L"Director %s\n"); + addPair("Exclude %s\n", L"Excludeți %s\n"); + addPair("Exclude (unmatched) %s\n", L"Excludeți (necompensată) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatat %s neschimbat "); + addPair(" seconds ", L" secunde "); + addPair("%d min %d sec ", L"%d min %d sec "); + addPair("%s lines\n", L"%s linii\n"); + addPair("Using default options file %s\n", L"Fișier folosind opțiunile implicite %s\n"); + addPair("Opening HTML documentation %s\n", L"Documentație HTML deschidere %s\n"); + addPair("Invalid option file options:", L"Opțiuni de opțiune de fișier nevalide:"); + addPair("Invalid command line options:", L"Opțiuni de linie de comandă nevalide:"); + addPair("For help on options type 'astyle -h'", L"Pentru ajutor cu privire la tipul de opțiuni 'astyle -h'"); + addPair("Cannot open options file", L"Nu se poate deschide fișierul de opțiuni"); + addPair("Cannot open directory", L"Nu se poate deschide directorul"); + addPair("Cannot open HTML file %s\n", L"Nu se poate deschide fișierul HTML %s\n"); + addPair("Command execute failure", L"Comandă executa eșec"); + addPair("Command is not installed", L"Comanda nu este instalat"); + addPair("Missing filename in %s\n", L"Lipsă nume de fișier %s\n"); + addPair("Recursive option with no wildcard", L"Opțiunea recursiv cu nici un wildcard"); + addPair("Did you intend quote the filename", L"V-intentionati cita numele de fișier"); + addPair("No file to process %s\n", L"Nu există un fișier pentru a procesa %s\n"); + addPair("Did you intend to use --recursive", L"V-ați intenționați să utilizați --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nu se poate procesa codificarea UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style a terminat"); +} + Russian::Russian() // русский // build the translation vector in the Translation base class { diff --git a/src/ASLocalizer.h b/src/ASLocalizer.h index b3c8033..037dcb7 100644 --- a/src/ASLocalizer.h +++ b/src/ASLocalizer.h @@ -1,28 +1,8 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASLocalizer.h - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// ASLocalizer.h +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + #ifndef ASLOCALIZER_H #define ASLOCALIZER_H @@ -45,26 +25,26 @@ class Translation; class ASLocalizer { - public: // functions - ASLocalizer(); - virtual ~ASLocalizer(); - string getLanguageID() const; - const Translation* getTranslationClass() const; +public: // functions + ASLocalizer(); + virtual ~ASLocalizer(); + string getLanguageID() const; + const Translation* getTranslationClass() const; #ifdef _WIN32 - void setLanguageFromLCID(size_t lcid); + void setLanguageFromLCID(size_t lcid); #endif - void setLanguageFromName(const char* langID); - const char* settext(const char* textIn) const; + void setLanguageFromName(const char* langID); + const char* settext(const char* textIn) const; - private: // functions - void setTranslationClass(); +private: // functions + void setTranslationClass(); - private: // variables - Translation* m_translation; // pointer to a polymorphic Translation class - string m_langID; // language identifier from the locale - string m_subLangID; // sub language identifier, if needed - string m_localeName; // name of the current locale (Linux only) - size_t m_lcid; // LCID of the user locale (Windows only) +private: // variables + Translation* m_translation; // pointer to a polymorphic Translation class + string m_langID; // language identifier from the locale + string m_subLangID; // sub language identifier, if needed + string m_localeName; // name of the current locale (Linux only) + size_t m_lcid; // LCID of the user locale (Windows only) }; //---------------------------------------------------------------------------- @@ -79,18 +59,21 @@ class Translation // NOTE: This class must have virtual methods for typeid() to work. // typeid() is used by AStyleTestI18n_Localizer.cpp. { - public: - Translation() {} - virtual ~Translation() {} - string convertToMultiByte(const wstring &wideStr) const; - size_t getTranslationVectorSize() const; - bool getWideTranslation(const string &stringIn, wstring &wideOut) const; - string &translate(const string &stringIn) const; +public: + Translation() {} + virtual ~Translation() {} + string convertToMultiByte(const wstring& wideStr) const; + size_t getTranslationVectorSize() const; + bool getWideTranslation(const string& stringIn, wstring& wideOut) const; + string& translate(const string& stringIn) const; - protected: - void addPair(const string &english, const wstring &translated); - // variables - vector > m_translation; // translation vector +protected: + void addPair(const string& english, const wstring& translated); + // variables + vector > m_translation; // translation vector + +private: + mutable string m_mbTranslation; }; //---------------------------------------------------------------------------- @@ -99,107 +82,74 @@ class Translation // These classes have only a constructor which builds the language vector. //---------------------------------------------------------------------------- +class Bulgarian : public Translation +{ public: Bulgarian(); }; + class ChineseSimplified : public Translation -{ - public: - ChineseSimplified(); -}; +{ public: ChineseSimplified(); }; class ChineseTraditional : public Translation -{ - public: - ChineseTraditional(); -}; +{ public: ChineseTraditional(); }; class Dutch : public Translation -{ - public: - Dutch(); -}; +{ public: Dutch(); }; class English : public Translation -{ - public: - English(); -}; +{ public: English(); }; + +class Estonian : public Translation +{ public: Estonian(); }; class Finnish : public Translation -{ - public: - Finnish(); -}; +{ public: Finnish(); }; class French : public Translation -{ - public: - French(); -}; +{ public: French(); }; class German : public Translation -{ - public: - German(); -}; +{ public: German(); }; + +class Greek : public Translation +{ public: Greek(); }; class Hindi : public Translation -{ - public: - Hindi(); -}; +{ public: Hindi(); }; + +class Hungarian : public Translation +{ public: Hungarian(); }; class Italian : public Translation -{ - public: - Italian(); -}; +{ public: Italian(); }; class Japanese : public Translation -{ - public: - Japanese(); -}; +{ public: Japanese(); }; class Korean : public Translation -{ - public: - Korean(); -}; +{ public: Korean(); }; + +class Norwegian : public Translation +{ public: Norwegian(); }; class Polish : public Translation -{ - public: - Polish(); -}; +{ public: Polish(); }; class Portuguese : public Translation -{ - public: - Portuguese(); -}; +{ public: Portuguese(); }; + +class Romanian : public Translation +{ public: Romanian(); }; class Russian : public Translation -{ - public: - Russian(); -}; +{ public: Russian(); }; class Spanish : public Translation -{ - public: - Spanish(); -}; +{ public: Spanish(); }; class Swedish : public Translation -{ - public: - Swedish(); -}; +{ public: Swedish(); }; class Ukrainian : public Translation -{ - public: - Ukrainian(); -}; +{ public: Ukrainian(); }; #endif // ASTYLE_LIB diff --git a/src/ASResource.cpp b/src/ASResource.cpp index 0c430f4..f7e000f 100644 --- a/src/ASResource.cpp +++ b/src/ASResource.cpp @@ -1,35 +1,21 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * ASResource.cpp - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// ASResource.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- #include "astyle.h" #include +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- namespace astyle { - +// const string ASResource::AS_IF = string("if"); const string ASResource::AS_ELSE = string("else"); const string ASResource::AS_FOR = string("for"); @@ -62,6 +48,7 @@ const string ASResource::AS_TRY = string("try"); const string ASResource::AS_CATCH = string("catch"); const string ASResource::AS_THROW = string("throw"); const string ASResource::AS_FINALLY = string("finally"); +const string ASResource::AS_USING = string("using"); const string ASResource::_AS_TRY = string("__try"); const string ASResource::_AS_FINALLY = string("__finally"); const string ASResource::_AS_EXCEPT = string("__except"); @@ -277,6 +264,7 @@ void ASResource::buildHeaders(vector* headers, int fileType, bool headers->push_back(&AS_SET); headers->push_back(&AS_ADD); headers->push_back(&AS_REMOVE); + headers->push_back(&AS_USING); } if (beautifier) @@ -315,17 +303,19 @@ void ASResource::buildIndentableHeaders(vector* indentableHeaders */ void ASResource::buildIndentableMacros(vector* >* indentableMacros) { - // the pairs must be retained in memory - static const struct pair macros[] = + typedef pair macro_pair; + + // the pairs must be retained in memory because of pair pointers + static const macro_pair macros[] = { // wxWidgets - make_pair("BEGIN_EVENT_TABLE", "END_EVENT_TABLE"), - make_pair("wxBEGIN_EVENT_TABLE", "wxEND_EVENT_TABLE"), + macro_pair("BEGIN_EVENT_TABLE", "END_EVENT_TABLE"), + macro_pair("wxBEGIN_EVENT_TABLE", "wxEND_EVENT_TABLE"), // MFC - make_pair("BEGIN_DISPATCH_MAP", "END_DISPATCH_MAP"), - make_pair("BEGIN_EVENT_MAP", "END_EVENT_MAP"), - make_pair("BEGIN_MESSAGE_MAP", "END_MESSAGE_MAP"), - make_pair("BEGIN_PROPPAGEIDS", "END_PROPPAGEIDS"), + macro_pair("BEGIN_DISPATCH_MAP", "END_DISPATCH_MAP"), + macro_pair("BEGIN_EVENT_MAP", "END_EVENT_MAP"), + macro_pair("BEGIN_MESSAGE_MAP", "END_MESSAGE_MAP"), + macro_pair("BEGIN_PROPPAGEIDS", "END_PROPPAGEIDS"), }; size_t elements = sizeof(macros) / sizeof(macros[0]); @@ -570,7 +560,7 @@ void ASResource::buildPreDefinitionHeaders(vector* preDefinitionH * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // 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 @@ -586,7 +576,7 @@ bool ASBase::findKeyword(const string &line, int i, const string &keyword) const if (isLegalNameChar(line[wordEnd])) return false; // is not a keyword if part of a definition - const char peekChar = peekNextChar(line, wordEnd - 1); + const char peekChar = peekNextChar(line, (int)wordEnd - 1); if (peekChar == ',' || peekChar == ')') return false; return true; @@ -594,7 +584,7 @@ bool ASBase::findKeyword(const string &line, int i, const string &keyword) const // get the current word on a line // index must point to the beginning of the word -string ASBase::getCurrentWord(const string &line, size_t index) const +string ASBase::getCurrentWord(const string& line, size_t index) const { assert(isCharPotentialHeader(line, index)); size_t lineLength = line.length(); @@ -607,4 +597,71 @@ string ASBase::getCurrentWord(const string &line, size_t index) const return line.substr(index, i - index); } +// check if a specific character can be used in a legal variable/method/class name +bool ASBase::isLegalNameChar(char ch) const +{ + if (isWhiteSpace(ch)) return false; + if ((unsigned) ch > 127) return false; + return (isalnum((unsigned char) ch) + || ch == '.' || ch == '_' + || (isJavaStyle() && ch == '$') + || (isSharpStyle() && ch == '@')); // may be used as a prefix +} + +// check if a specific character can be part of a header +bool ASBase::isCharPotentialHeader(const string& line, size_t i) const +{ + assert(!isWhiteSpace(line[i])); + char prevCh = ' '; + if (i > 0) prevCh = line[i - 1]; + if (!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) + return true; + return false; +} + +// check if a specific character can be part of an operator +bool ASBase::isCharPotentialOperator(char ch) const +{ + assert(!isWhiteSpace(ch)); + if ((unsigned) ch > 127) return false; + return (ispunct((unsigned char) ch) + && ch != '{' && ch != '}' + && ch != '(' && ch != ')' + && ch != '[' && ch != ']' + && ch != ';' && ch != ',' + && ch != '#' && ch != '\\' + && ch != '\'' && ch != '\"'); +} + +// check if a specific character is a digit +// NOTE: Visual C isdigit() gives assert error if char > 256 +bool ASBase::isDigit(char ch) const +{ + return (ch >= '0' && ch <= '9'); +} + +// check if a specific character is a digit separator +bool ASBase::isDigitSeparator(const string& line, int i) const +{ + assert(line[i] == '\''); + // casting to (unsigned char) eliminates negative characters + // will get a "Debug Assertion Failed" if not cast + bool foundDigitSeparator = i > 0 + && isxdigit((unsigned char) line[i - 1]) + && i < (int) line.length() - 1 + && isxdigit((unsigned char) line[i + 1]); + return foundDigitSeparator; +} + +// peek at the next unread character. +char ASBase::peekNextChar(const string& line, int i) const +{ + char ch = ' '; + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if (peekNum == string::npos) + return ch; + ch = line[peekNum]; + return ch; +} + } // end namespace astyle diff --git a/src/astyle.h b/src/astyle.h index 19abc44..c910942 100644 --- a/src/astyle.h +++ b/src/astyle.h @@ -1,32 +1,15 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * astyle.h - - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// astyle.h +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. #ifndef ASTYLE_H #define ASTYLE_H +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + #ifdef __VMS #define __USE_STD_IOSTREAM 1 #include @@ -39,13 +22,16 @@ #include #include +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- + #ifdef __GNUC__ - #include // need both string and string.h for GCC + #include // need both string and string.h for GCC #endif #ifdef _MSC_VER - #pragma warning(disable: 4996) // secure version deprecation warnings - #pragma warning(disable: 4267) // 64 bit signed/unsigned loss of data + #pragma warning(disable: 4267) // conversion from size_t to int #endif #ifdef __BORLANDC__ @@ -61,10 +47,18 @@ #pragma clang diagnostic ignored "-Wshorten-64-to-32" #endif -namespace astyle { +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- +namespace astyle { +// using namespace std; +//---------------------------------------------------------------------------- +// definitions +//---------------------------------------------------------------------------- + enum FileType { C_TYPE = 0, JAVA_TYPE = 1, SHARP_TYPE = 2 }; /* The enums below are not recognized by 'vectors' in Microsoft Visual C++ @@ -181,15 +175,15 @@ enum LineEndFormat class ASSourceIterator { - public: - ASSourceIterator() {} - virtual ~ASSourceIterator() {} - virtual int getStreamLength() const = 0; - virtual bool hasMoreLines() const = 0; - virtual string nextLine(bool emptyLineWasDeleted = false) = 0; - virtual string peekNextLine() = 0; - virtual void peekReset() = 0; - virtual streamoff tellg() = 0; +public: + ASSourceIterator() {} + virtual ~ASSourceIterator() {} + virtual int getStreamLength() const = 0; + virtual bool hasMoreLines() const = 0; + virtual string nextLine(bool emptyLineWasDeleted = false) = 0; + virtual string peekNextLine() = 0; + virtual void peekReset() = 0; + virtual streamoff tellg() = 0; }; //----------------------------------------------------------------------------- @@ -198,138 +192,94 @@ class ASSourceIterator class ASResource { - public: - ASResource() {} - virtual ~ASResource() {} - void buildAssignmentOperators(vector* assignmentOperators); - void buildCastOperators(vector* castOperators); - void buildHeaders(vector* headers, int fileType, bool beautifier = false); - void buildIndentableMacros(vector* >* indentableMacros); - void buildIndentableHeaders(vector* indentableHeaders); - void buildNonAssignmentOperators(vector* nonAssignmentOperators); - void buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier = false); - void buildOperators(vector* operators, int fileType); - void buildPreBlockStatements(vector* preBlockStatements, int fileType); - void buildPreCommandHeaders(vector* preCommandHeaders, int fileType); - void buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType); +public: + ASResource() {} + virtual ~ASResource() {} + void buildAssignmentOperators(vector* assignmentOperators); + void buildCastOperators(vector* castOperators); + void buildHeaders(vector* headers, int fileType, bool beautifier = false); + void buildIndentableMacros(vector* >* indentableMacros); + void buildIndentableHeaders(vector* indentableHeaders); + void buildNonAssignmentOperators(vector* nonAssignmentOperators); + void buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier = false); + void buildOperators(vector* operators, int fileType); + void buildPreBlockStatements(vector* preBlockStatements, int fileType); + void buildPreCommandHeaders(vector* preCommandHeaders, int fileType); + void buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType); - public: - static const string AS_IF, AS_ELSE; - static const string AS_DO, AS_WHILE; - static const string AS_FOR; - static const string AS_SWITCH, AS_CASE, AS_DEFAULT; - static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY; - static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT; - 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_END; - static const string AS_SELECTOR; - static const string AS_EXTERN, AS_ENUM; - static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW; - static const string AS_NOEXCEPT, AS_INTERRUPT, AS_AUTORELEASEPOOL; - static const string AS_WHERE, AS_LET, 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; - static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; - static const string AS_RETURN; - static const string AS_CIN, AS_COUT, AS_CERR; - static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; - static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; - static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN; - static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN; - static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL, AS_GR_GR_GR, AS_GR_GR; - static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; - static const string AS_QUESTION_QUESTION, AS_LAMBDA; - static const string AS_ARROW, AS_AND, AS_OR; - static const string AS_SCOPE_RESOLUTION; - 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; - static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM; - static const string AS_QFOREACH, AS_QFOREVER, AS_FOREVER; - static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED; - static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE; - static const string AS_DELEGATE, AS_UNCHECKED; - static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; - static const string AS_NS_DURING, AS_NS_HANDLER; +public: + static const string AS_IF, AS_ELSE; + static const string AS_DO, AS_WHILE; + static const string AS_FOR; + static const string AS_SWITCH, AS_CASE, AS_DEFAULT; + static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY, AS_USING; + static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT; + 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_END; + static const string AS_SELECTOR; + static const string AS_EXTERN, AS_ENUM; + static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW; + static const string AS_NOEXCEPT, AS_INTERRUPT, AS_AUTORELEASEPOOL; + static const string AS_WHERE, AS_LET, 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; + static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; + static const string AS_RETURN; + static const string AS_CIN, AS_COUT, AS_CERR; + static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; + static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; + static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN; + static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN; + static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL, AS_GR_GR_GR, AS_GR_GR; + static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; + static const string AS_QUESTION_QUESTION, AS_LAMBDA; + static const string AS_ARROW, AS_AND, AS_OR; + static const string AS_SCOPE_RESOLUTION; + 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; + static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM; + static const string AS_QFOREACH, AS_QFOREVER, AS_FOREVER; + static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED; + static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE; + static const string AS_DELEGATE, AS_UNCHECKED; + static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; + static const string AS_NS_DURING, AS_NS_HANDLER; }; // Class ASResource //----------------------------------------------------------------------------- // Class ASBase +// Functions definitions are at the end of ASResource.cpp. //----------------------------------------------------------------------------- class ASBase { - private: - // all variables should be set by the "init" function - int baseFileType; // a value from enum FileType +private: + // all variables should be set by the "init" function + int baseFileType; // a value from enum FileType - protected: - ASBase() : baseFileType(C_TYPE) { } - virtual ~ASBase() {} +protected: + ASBase() : baseFileType(C_TYPE) { } - // functions definitions are at the end of ASResource.cpp - bool findKeyword(const string &line, int i, const string &keyword) const; - string getCurrentWord(const string &line, size_t index) const; +protected: // inline functions + void init(int fileTypeArg) { baseFileType = fileTypeArg; } + bool isCStyle() const { return (baseFileType == C_TYPE); } + bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); } + bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); } + bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } - protected: - void init(int fileTypeArg) { baseFileType = fileTypeArg; } - bool isCStyle() const { return (baseFileType == C_TYPE); } - bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); } - bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); } +protected: // functions definitions are at the end of ASResource.cpp + bool findKeyword(const string& line, int i, const string& keyword) const; + string getCurrentWord(const string& line, size_t index) const; + bool isDigit(char ch) const; + bool isLegalNameChar(char ch) const; + bool isCharPotentialHeader(const string& line, size_t i) const; + bool isCharPotentialOperator(char ch) const; + bool isDigitSeparator(const string& line, int i) const; + char peekNextChar(const string& line, int i) const; - // check if a specific character is a digit - // NOTE: Visual C isdigit() gives assert error if char > 256 - bool isDigit(char ch) const { - return (ch >= '0' && ch <= '9'); - } - - // check if a specific character can be used in a legal variable/method/class name - bool isLegalNameChar(char ch) const { - if (isWhiteSpace(ch)) return false; - if ((unsigned) ch > 127) return false; - return (isalnum((unsigned char)ch) - || ch == '.' || ch == '_' - || (isJavaStyle() && ch == '$') - || (isSharpStyle() && ch == '@')); // may be used as a prefix - } - - // check if a specific character can be part of a header - bool isCharPotentialHeader(const string &line, size_t i) const { - assert(!isWhiteSpace(line[i])); - char prevCh = ' '; - if (i > 0) prevCh = line[i - 1]; - if (!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) - return true; - return false; - } - - // check if a specific character can be part of an operator - bool isCharPotentialOperator(char ch) const { - assert(!isWhiteSpace(ch)); - if ((unsigned) ch > 127) return false; - return (ispunct((unsigned char)ch) - && ch != '{' && ch != '}' - && ch != '(' && ch != ')' - && ch != '[' && ch != ']' - && ch != ';' && ch != ',' - && ch != '#' && ch != '\\' - && ch != '\'' && ch != '\"'); - } - - // check if a specific character is a whitespace character - bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } - - // peek at the next unread character. - 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) - return ch; - ch = line[peekNum]; - return ch; - } }; // Class ASBase //----------------------------------------------------------------------------- @@ -338,233 +288,235 @@ class ASBase class ASBeautifier : protected ASResource, protected ASBase { - public: - ASBeautifier(); - virtual ~ASBeautifier(); - virtual void init(ASSourceIterator* iter); - virtual string beautify(const string &line); - void setCaseIndent(bool state); - void setClassIndent(bool state); - void setCStyle(); - void setDefaultTabLength(); - void setEmptyLineFill(bool state); - void setForceTabXIndentation(int length); - void setJavaStyle(); - void setLabelIndent(bool state); - void setMaxInStatementIndentLength(int max); - void setMinConditionalIndentOption(int min); - void setMinConditionalIndentLength(); - void setModeManuallySet(bool state); - void setModifierIndent(bool state); - void setNamespaceIndent(bool state); - void setAlignMethodColon(bool state); - void setSharpStyle(); - void setSpaceIndentation(int length = 4); - void setSwitchIndent(bool state); - void setTabIndentation(int length = 4, bool forceTabs = false); - void setPreprocDefineIndent(bool state); - void setPreprocConditionalIndent(bool state); - int getBeautifierFileType() const; - int getFileType() const; - int getIndentLength(void) const; - int getTabLength(void) const; - string getIndentString(void) const; - string getNextWord(const string &line, size_t currPos) const; - bool getBracketIndent(void) const; - bool getBlockIndent(void) const; - bool getCaseIndent(void) const; - bool getClassIndent(void) const; - bool getEmptyLineFill(void) const; - bool getForceTabIndentation(void) const; - bool getModeManuallySet(void) const; - bool getModifierIndent(void) const; - bool getNamespaceIndent(void) const; - bool getPreprocDefineIndent(void) const; - bool getSwitchIndent(void) const; +public: + ASBeautifier(); + virtual ~ASBeautifier(); + virtual void init(ASSourceIterator* iter); + virtual string beautify(const string& line); + void setCaseIndent(bool state); + void setClassIndent(bool state); + void setCStyle(); + void setDefaultTabLength(); + void setEmptyLineFill(bool state); + void setForceTabXIndentation(int length); + void setJavaStyle(); + void setLabelIndent(bool state); + void setMaxInStatementIndentLength(int max); + void setMinConditionalIndentOption(int min); + void setMinConditionalIndentLength(); + void setModeManuallySet(bool state); + void setModifierIndent(bool state); + void setNamespaceIndent(bool state); + void setAlignMethodColon(bool state); + void setSharpStyle(); + void setSpaceIndentation(int length = 4); + void setSwitchIndent(bool state); + void setTabIndentation(int length = 4, bool forceTabs = false); + void setPreprocDefineIndent(bool state); + void setPreprocConditionalIndent(bool state); + int getBeautifierFileType() const; + int getFileType() const; + int getIndentLength(void) const; + int getTabLength(void) const; + string getIndentString(void) const; + string getNextWord(const string& line, size_t currPos) const; + bool getAlignMethodColon(void) const; + bool getBracketIndent(void) const; + bool getBlockIndent(void) const; + bool getCaseIndent(void) const; + bool getClassIndent(void) const; + bool getEmptyLineFill(void) const; + bool getForceTabIndentation(void) const; + bool getModeManuallySet(void) const; + bool getModifierIndent(void) const; + bool getNamespaceIndent(void) const; + bool getPreprocDefineIndent(void) const; + bool getSwitchIndent(void) const; - protected: - void deleteBeautifierVectors(); - const string* findHeader(const string &line, int i, - const vector* possibleHeaders) const; - 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) const; - void setBlockIndent(bool state); - void setBracketIndent(bool state); - void setBracketIndentVtk(bool state); - string extractPreprocessorStatement(const string &line) const; - string trim(const string &str) const; - string rtrim(const string &str) const; +protected: + void deleteBeautifierVectors(); + const string* findHeader(const string& line, int i, + const vector* possibleHeaders) const; + 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) const; + void setBlockIndent(bool state); + void setBracketIndent(bool state); + void setBracketIndentVtk(bool state); + string extractPreprocessorStatement(const string& line) const; + string trim(const string& str) const; + string rtrim(const string& str) const; - // variables set by ASFormatter - must be updated in activeBeautifierStack - int inLineNumber; - int horstmannIndentInStatement; - int nonInStatementBracket; - bool lineCommentNoBeautify; - bool isElseHeaderIndent; - bool isCaseHeaderCommentIndent; - bool isNonInStatementArray; - bool isSharpAccessor; - bool isSharpDelegate; - bool isInExternC; - bool isInBeautifySQL; - bool isInIndentableStruct; - bool isInIndentablePreproc; + // variables set by ASFormatter - must be updated in activeBeautifierStack + int inLineNumber; + int horstmannIndentInStatement; + int nonInStatementBracket; + int objCColonAlignSubsequent; // for subsequent lines not counting indent + bool lineCommentNoBeautify; + bool isElseHeaderIndent; + bool isCaseHeaderCommentIndent; + bool isNonInStatementArray; + bool isSharpAccessor; + bool isSharpDelegate; + bool isInExternC; + bool isInBeautifySQL; + bool isInIndentableStruct; + bool isInIndentablePreproc; - private: // functions - ASBeautifier(const ASBeautifier ©); - ASBeautifier &operator=(ASBeautifier &); // not to be implemented +private: // functions + ASBeautifier(const ASBeautifier& copy); // inline functions + ASBeautifier& operator=(ASBeautifier&); // not to be implemented - void adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent); - void computePreliminaryIndentation(); - void parseCurrentLine(const string &line); - void popLastInStatementIndent(); - void processPreprocessor(const string &preproc, const string &line); - void registerInStatementIndent(const string &line, int i, int spaceIndentCount, - int tabIncrementIn, int minIndent, bool updateParenStack); - void registerInStatementIndentColon(const string &line, int i, int tabIncrementIn); - void initVectors(); - void initTempStacksContainer(vector*>* &container, - vector*>* value); - void clearObjCMethodDefinitionAlignment(); - void deleteBeautifierContainer(vector* &container); - void deleteTempStacksContainer(vector*>* &container); - int adjustIndentCountForBreakElseIfComments() const; - int computeObjCColonAlignment(string &line, int colonAlignPosition) const; - int convertTabToSpaces(int i, int tabIncrementIn) const; - int getInStatementIndentAssign(const string &line, size_t currPos) const; - int getInStatementIndentComma(const string &line, size_t currPos) const; - bool isIndentedPreprocessor(const string &line, size_t currPos) const; - bool isLineEndComment(const string &line, int startPos) const; - bool isPreprocessorConditionalCplusplus(const string &line) const; - bool isInPreprocessorUnterminatedComment(const string &line); - bool statementEndsWithComma(const string &line, int index) const; - string &getIndentedLineReturn(string &newLine, const string &originalLine) const; - string preLineWS(int lineIndentCount, int lineSpaceIndentCount) const; - template void deleteContainer(T &container); - template void initContainer(T &container, T value); - vector*>* copyTempStacks(const ASBeautifier &other) const; - pair computePreprocessorIndent(); + void adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent); + void computePreliminaryIndentation(); + void parseCurrentLine(const string& line); + void popLastInStatementIndent(); + void processPreprocessor(const string& preproc, const string& line); + void registerInStatementIndent(const string& line, int i, int spaceIndentCount, + int tabIncrementIn, int minIndent, bool updateParenStack); + void registerInStatementIndentColon(const string& line, int i, int tabIncrementIn); + void initVectors(); + void initTempStacksContainer(vector*>*& container, + vector*>* value); + void clearObjCMethodDefinitionAlignment(); + void deleteBeautifierContainer(vector*& container); + void deleteTempStacksContainer(vector*>*& container); + int adjustIndentCountForBreakElseIfComments() const; + int computeObjCColonAlignment(string& line, int colonAlignPosition) const; + int convertTabToSpaces(int i, int tabIncrementIn) const; + int getInStatementIndentAssign(const string& line, size_t currPos) const; + int getInStatementIndentComma(const string& line, size_t currPos) const; + bool isIndentedPreprocessor(const string& line, size_t currPos) const; + bool isLineEndComment(const string& line, int startPos) const; + bool isPreprocessorConditionalCplusplus(const string& line) const; + bool isInPreprocessorUnterminatedComment(const string& line); + bool statementEndsWithComma(const string& line, int index) const; + string& getIndentedLineReturn(string& newLine, const string& originalLine) const; + string preLineWS(int lineIndentCount, int lineSpaceIndentCount) const; + template void deleteContainer(T& container); + template void initContainer(T& container, T value); + vector*>* copyTempStacks(const ASBeautifier& other) const; + pair computePreprocessorIndent(); - private: // variables - int beautifierFileType; - vector* headers; - vector* nonParenHeaders; - vector* preBlockStatements; - vector* preCommandHeaders; - vector* assignmentOperators; - vector* nonAssignmentOperators; - vector* indentableHeaders; +private: // variables + int beautifierFileType; + vector* headers; + vector* nonParenHeaders; + vector* preBlockStatements; + vector* preCommandHeaders; + vector* assignmentOperators; + vector* nonAssignmentOperators; + vector* indentableHeaders; - vector* waitingBeautifierStack; - vector* activeBeautifierStack; - vector* waitingBeautifierStackLengthStack; - vector* activeBeautifierStackLengthStack; - vector* headerStack; - vector* >* tempStacks; - vector* blockParenDepthStack; - vector* blockStatementStack; - vector* parenStatementStack; - vector* bracketBlockStateStack; - vector* inStatementIndentStack; - vector* inStatementIndentStackSizeStack; - vector* parenIndentStack; - vector >* preprocIndentStack; + vector* waitingBeautifierStack; + vector* activeBeautifierStack; + vector* waitingBeautifierStackLengthStack; + vector* activeBeautifierStackLengthStack; + vector* headerStack; + vector* >* tempStacks; + vector* blockParenDepthStack; + vector* blockStatementStack; + vector* parenStatementStack; + vector* bracketBlockStateStack; + vector* inStatementIndentStack; + vector* inStatementIndentStackSizeStack; + vector* parenIndentStack; + vector >* preprocIndentStack; - ASSourceIterator* sourceIterator; - const string* currentHeader; - const string* previousLastLineHeader; - const string* probationHeader; - const string* lastLineHeader; - string indentString; - string verbatimDelimiter; - bool isInQuote; - bool isInVerbatimQuote; - bool haveLineContinuationChar; - bool isInAsm; - bool isInAsmOneLine; - bool isInAsmBlock; - bool isInComment; - bool isInPreprocessorComment; - bool isInHorstmannComment; - bool isInCase; - bool isInQuestion; - bool isInStatement; - bool isInHeader; - bool isInTemplate; - bool isInDefine; - bool isInDefineDefinition; - bool classIndent; - bool isIndentModeOff; - bool isInClassHeader; // is in a class before the opening bracket - bool isInClassHeaderTab; // is in an indentable class header line - bool isInClassInitializer; // is in a class after the ':' initializer - bool isInClass; // is in a class after the opening bracket - bool isInObjCMethodDefinition; - bool isImmediatelyPostObjCMethodDefinition; - bool isInIndentablePreprocBlock; - bool isInObjCInterface; - bool isInEnum; - bool isInEnumTypeID; - bool isInLet; - bool modifierIndent; - bool switchIndent; - bool caseIndent; - bool namespaceIndent; - bool bracketIndent; - bool bracketIndentVtk; - bool blockIndent; - bool labelIndent; - bool shouldIndentPreprocDefine; - bool isInConditional; - bool isModeManuallySet; - bool shouldForceTabIndentation; - bool emptyLineFill; - bool backslashEndsPrevLine; - bool lineOpensWithLineComment; - bool lineOpensWithComment; - bool lineStartsInComment; - bool blockCommentNoIndent; - bool blockCommentNoBeautify; - bool previousLineProbationTab; - bool lineBeginsWithOpenBracket; - bool lineBeginsWithCloseBracket; - bool lineBeginsWithComma; - bool lineIsCommentOnly; - bool lineIsLineCommentOnly; - bool shouldIndentBrackettedLine; - bool isInSwitch; - bool foundPreCommandHeader; - bool foundPreCommandMacro; - bool shouldAlignMethodColon; - bool shouldIndentPreprocConditional; - int indentCount; - int spaceIndentCount; - int spaceIndentObjCMethodDefinition; - int colonIndentObjCMethodDefinition; - int lineOpeningBlocksNum; - int lineClosingBlocksNum; - int fileType; - int minConditionalOption; - int minConditionalIndent; - int parenDepth; - int indentLength; - int tabLength; - int blockTabCount; - int maxInStatementIndent; - int classInitializerIndents; - int templateDepth; - int squareBracketCount; - int prevFinalLineSpaceIndentCount; - int prevFinalLineIndentCount; - int defineIndentCount; - int preprocBlockIndent; - char quoteChar; - char prevNonSpaceCh; - char currentNonSpaceCh; - char currentNonLegalCh; - char prevNonLegalCh; + ASSourceIterator* sourceIterator; + const string* currentHeader; + const string* previousLastLineHeader; + const string* probationHeader; + const string* lastLineHeader; + string indentString; + string verbatimDelimiter; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isInComment; + bool isInPreprocessorComment; + bool isInHorstmannComment; + bool isInCase; + bool isInQuestion; + bool isInStatement; + bool isInHeader; + bool isInTemplate; + bool isInDefine; + bool isInDefineDefinition; + bool classIndent; + bool isIndentModeOff; + bool isInClassHeader; // is in a class before the opening bracket + bool isInClassHeaderTab; // is in an indentable class header line + bool isInClassInitializer; // is in a class after the ':' initializer + bool isInClass; // is in a class after the opening bracket + bool isInObjCMethodDefinition; + bool isImmediatelyPostObjCMethodDefinition; + bool isInIndentablePreprocBlock; + bool isInObjCInterface; + bool isInEnum; + bool isInEnumTypeID; + bool isInLet; + bool modifierIndent; + bool switchIndent; + bool caseIndent; + bool namespaceIndent; + bool bracketIndent; + bool bracketIndentVtk; + bool blockIndent; + bool labelIndent; + bool shouldIndentPreprocDefine; + bool isInConditional; + bool isModeManuallySet; + bool shouldForceTabIndentation; + bool emptyLineFill; + bool backslashEndsPrevLine; + bool lineOpensWithLineComment; + bool lineOpensWithComment; + bool lineStartsInComment; + bool blockCommentNoIndent; + bool blockCommentNoBeautify; + bool previousLineProbationTab; + bool lineBeginsWithOpenBracket; + bool lineBeginsWithCloseBracket; + bool lineBeginsWithComma; + bool lineIsCommentOnly; + bool lineIsLineCommentOnly; + bool shouldIndentBrackettedLine; + bool isInSwitch; + bool foundPreCommandHeader; + bool foundPreCommandMacro; + bool shouldAlignMethodColon; + bool shouldIndentPreprocConditional; + int indentCount; + int spaceIndentCount; + int spaceIndentObjCMethodDefinition; + int colonIndentObjCMethodDefinition; + int lineOpeningBlocksNum; + int lineClosingBlocksNum; + int fileType; + int minConditionalOption; + int minConditionalIndent; + int parenDepth; + int indentLength; + int tabLength; + int blockTabCount; + int maxInStatementIndent; + int classInitializerIndents; + int templateDepth; + int squareBracketCount; + int prevFinalLineSpaceIndentCount; + int prevFinalLineIndentCount; + int defineIndentCount; + int preprocBlockIndent; + char quoteChar; + char prevNonSpaceCh; + char currentNonSpaceCh; + char currentNonLegalCh; + char prevNonLegalCh; }; // Class ASBeautifier //----------------------------------------------------------------------------- @@ -573,72 +525,72 @@ class ASBeautifier : protected ASResource, protected ASBase class ASEnhancer : protected ASBase { - public: // functions - ASEnhancer(); - virtual ~ASEnhancer(); - void init(int, int, int, bool, bool, bool, bool, bool, bool, bool, - vector* >*); - void enhance(string &line, bool isInNamespace, bool isInPreprocessor, bool isInSQL); +public: // functions + ASEnhancer(); + virtual ~ASEnhancer(); + void init(int, int, int, bool, bool, bool, bool, bool, bool, bool, + vector* >*); + void enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL); - private: // functions - void convertForceTabIndentToSpaces(string &line) const; - void convertSpaceIndentToForceTab(string &line) 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; - bool isOneLineBlockReached(string &line, int startChar) const; - void parseCurrentLine(string &line, bool isInPreprocessor, bool isInSQL); - size_t processSwitchBlock(string &line, size_t index); - int unindentLine(string &line, int unindent) const; +private: // functions + void convertForceTabIndentToSpaces(string& line) const; + void convertSpaceIndentToForceTab(string& line) 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; + bool isOneLineBlockReached(string& line, int startChar) const; + void parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL); + size_t processSwitchBlock(string& line, size_t index); + int unindentLine(string& line, int unindent) const; - private: - // options from command line or options file - int indentLength; - int tabLength; - bool useTabs; - bool forceTab; - bool namespaceIndent; - bool caseIndent; - bool preprocBlockIndent; - bool preprocDefineIndent; - bool emptyLineFill; +private: + // options from command line or options file + int indentLength; + int tabLength; + bool useTabs; + bool forceTab; + bool namespaceIndent; + bool caseIndent; + bool preprocBlockIndent; + bool preprocDefineIndent; + bool emptyLineFill; - // parsing variables - int lineNumber; - bool isInQuote; - bool isInComment; - char quoteChar; + // parsing variables + int lineNumber; + bool isInQuote; + bool isInComment; + char quoteChar; - // unindent variables - int bracketCount; - int switchDepth; - int eventPreprocDepth; - bool lookingForCaseBracket; - bool unindentNextLine; - bool shouldUnindentLine; - bool shouldUnindentComment; + // unindent variables + int bracketCount; + int switchDepth; + int eventPreprocDepth; + bool lookingForCaseBracket; + bool unindentNextLine; + bool shouldUnindentLine; + bool shouldUnindentComment; - // struct used by ParseFormattedLine function - // contains variables used to unindent the case blocks - struct switchVariables - { - int switchBracketCount; - int unindentDepth; - bool unindentCase; - }; + // struct used by ParseFormattedLine function + // contains variables used to unindent the case blocks + struct SwitchVariables + { + int switchBracketCount; + int unindentDepth; + bool unindentCase; + }; - switchVariables sw; // switch variables struct - vector switchStack; // stack vector of switch variables + SwitchVariables sw; // switch variables struct + vector switchStack; // stack vector of switch variables - // event table variables - bool nextLineIsEventIndent; // begin event table indent is reached - bool isInEventTable; // need to indent an event table - vector* >* indentableMacros; + // event table variables + bool nextLineIsEventIndent; // begin event table indent is reached + bool isInEventTable; // need to indent an event table + vector* >* indentableMacros; - // SQL variables - bool nextLineIsDeclareIndent; // begin declare section indent is reached - bool isInDeclareSection; // need to indent a declare section + // SQL variables + bool nextLineIsDeclareIndent; // begin declare section indent is reached + bool isInDeclareSection; // need to indent a declare section }; // Class ASEnhancer @@ -648,373 +600,387 @@ class ASEnhancer : protected ASBase class ASFormatter : public ASBeautifier { - public: // functions - ASFormatter(); - virtual ~ASFormatter(); - virtual void init(ASSourceIterator* iter); - 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); - void setRemoveBracketsMode(bool state); - void setAttachClass(bool state); - void setAttachExternC(bool state); - void setAttachNamespace(bool state); - void setAttachInline(bool state); - void setBracketFormatMode(BracketMode mode); - void setBreakAfterMode(bool state); - void setBreakClosingHeaderBracketsMode(bool state); - void setBreakBlocksMode(bool state); - void setBreakClosingHeaderBlocksMode(bool state); - void setBreakElseIfsMode(bool state); - void setBreakOneLineBlocksMode(bool state); - void setMethodPrefixPaddingMode(bool state); - void setMethodPrefixUnPaddingMode(bool state); - void setCloseTemplatesMode(bool state); - void setDeleteEmptyLinesMode(bool state); - void setIndentCol1CommentsMode(bool state); - void setLineEndFormat(LineEndFormat fmt); - void setMaxCodeLength(int max); - void setObjCColonPaddingMode(ObjCColonPad mode); - void setOperatorPaddingMode(bool mode); - void setParensOutsidePaddingMode(bool mode); - void setParensFirstPaddingMode(bool mode); - void setParensInsidePaddingMode(bool mode); - void setParensHeaderPaddingMode(bool mode); - void setParensUnPaddingMode(bool state); - void setPointerAlignment(PointerAlign alignment); - void setPreprocBlockIndent(bool state); - void setReferenceAlignment(ReferenceAlign alignment); - void setSingleStatementsMode(bool state); - void setStripCommentPrefix(bool state); - void setTabSpaceConversionMode(bool state); - size_t getChecksumIn() const; - size_t getChecksumOut() const; - int getChecksumDiff() const; - int getFormatterFileType() const; +public: // functions + ASFormatter(); + virtual ~ASFormatter(); + virtual void init(ASSourceIterator* iter); + 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); + void setRemoveBracketsMode(bool state); + void setAttachClass(bool state); + void setAttachExternC(bool state); + void setAttachNamespace(bool state); + void setAttachInline(bool state); + void setBracketFormatMode(BracketMode mode); + void setBreakAfterMode(bool state); + void setBreakClosingHeaderBracketsMode(bool state); + void setBreakBlocksMode(bool state); + void setBreakClosingHeaderBlocksMode(bool state); + void setBreakElseIfsMode(bool state); + void setBreakOneLineBlocksMode(bool state); + void setMethodPrefixPaddingMode(bool state); + void setMethodPrefixUnPaddingMode(bool state); + void setReturnTypePaddingMode(bool state); + void setReturnTypeUnPaddingMode(bool state); + void setCloseTemplatesMode(bool state); + void setCommaPaddingMode(bool state); + void setDeleteEmptyLinesMode(bool state); + void setIndentCol1CommentsMode(bool state); + void setLineEndFormat(LineEndFormat fmt); + void setMaxCodeLength(int max); + void setObjCColonPaddingMode(ObjCColonPad mode); + void setOperatorPaddingMode(bool mode); + void setParensOutsidePaddingMode(bool mode); + void setParensFirstPaddingMode(bool mode); + void setParensInsidePaddingMode(bool mode); + void setParensHeaderPaddingMode(bool mode); + void setParensUnPaddingMode(bool state); + void setPointerAlignment(PointerAlign alignment); + void setPreprocBlockIndent(bool state); + void setReferenceAlignment(ReferenceAlign alignment); + void setSingleStatementsMode(bool state); + void setStripCommentPrefix(bool state); + void setTabSpaceConversionMode(bool state); + size_t getChecksumIn() const; + size_t getChecksumOut() const; + int getChecksumDiff() const; + int getFormatterFileType() const; - private: // functions - ASFormatter(const ASFormatter ©); // copy constructor not to be implemented - 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 adjustChecksumIn(int adjustment); - bool computeChecksumIn(const string ¤tLine_); - bool computeChecksumOut(const string &beautifiedLine); - bool addBracketsToStatement(); - bool removeBracketsFromStatement(); - bool commentAndHeaderFollows(); - bool getNextChar(); - bool getNextLine(bool emptyLineWasDeleted = false); - bool isArrayOperator() const; - bool isBeforeComment() const; - bool isBeforeAnyComment() const; - bool isBeforeAnyLineEndComment(int startPos) const; - bool isBeforeMultipleLineEndComments(int startPos) const; - bool isBracketType(BracketType a, BracketType b) const; - bool isClassInitializer() 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 isExternC() const; - bool isNextWordSharpNonParenHeader(int startChar) const; - bool isNonInStatementArrayBracket() const; - bool isOkToSplitFormattedLine(); - bool isPointerOrReference() const; - bool isPointerOrReferenceCentered() const; - bool isPointerOrReferenceVariable(string &word) const; - bool isSharpStyleWithParen(const string* header) const; - bool isStructAccessModified(string &firstLine, size_t index) const; - bool isIndentablePreprocessorBlock(string &firstLine, size_t index); - bool isUnaryOperator() const; - bool isUniformInitializerBracket() const; - bool isImmediatelyPostCast() const; - bool isInExponent() const; - bool isInSwitchStatement() const; - bool isNextCharOpeningBracket(int startChar) const; - bool isOkToBreakBlock(BracketType bracketType) const; - bool isOperatorPaddingDisabled() const; - bool pointerSymbolFollows() const; - int getCurrentLineCommentAdjustment(); - int getNextLineCommentAdjustment(); - int isOneLineBlockReached(string &line, int startChar) const; - void adjustComments(); - void appendChar(char ch, bool canBreakLine); - void appendCharInsideComments(); - void appendOperator(const string &sequence, bool canBreakLine = true); - void appendSequence(const string &sequence, bool canBreakLine = true); - void appendSpacePad(); - void appendSpaceAfter(); - void breakLine(bool isSplitLine = false); - void buildLanguageVectors(); - void updateFormattedLineSplitPoints(char appendedChar); - void updateFormattedLineSplitPointsOperator(const string &sequence); - void checkIfTemplateOpener(); - void clearFormattedLineSplitPoints(); - void convertTabToSpaces(); - void deleteContainer(vector* &container); - void formatArrayRunIn(); - void formatRunIn(); - void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); - void formatClosingBracket(BracketType bracketType); - void formatCommentBody(); - void formatCommentOpener(); - void formatCommentCloser(); - void formatLineCommentBody(); - void formatLineCommentOpener(); - void formatOpeningBracket(BracketType bracketType); - void formatQuoteBody(); - void formatQuoteOpener(); - void formatPointerOrReference(); - void formatPointerOrReferenceCast(); - void formatPointerOrReferenceToMiddle(); - void formatPointerOrReferenceToName(); - void formatPointerOrReferenceToType(); - void fixOptionVariableConflicts(); - void goForward(int i); - void isLineBreakBeforeClosingHeader(); - void initContainer(vector* &container, vector* value); - void initNewLine(); - void padObjCMethodColon(); - void padOperators(const string* newOperator); - void padParens(); - void processPreprocessor(); - void resetEndOfStatement(); - void setAttachClosingBracketMode(bool state); - void setBreakBlocksVariables(); - void stripCommentPrefix(); - void testForTimeToSplitFormattedLine(); - void trimContinuationLine(); - void updateFormattedLineSplitPointsPointerOrReference(size_t index); - size_t findFormattedLineSplitPoint() const; - size_t findNextChar(string &line, char searchChar, int searchStart = 0); - const string* checkForHeaderFollowingComment(const string &firstLine) const; - const string* getFollowingOperator() const; - string getPreviousWord(const string &line, int currPos) const; - string peekNextText(const string &firstLine, bool endOnEmptyLine = false, bool shouldReset = false) const; +private: // functions + ASFormatter(const ASFormatter& copy); // not to be implemented + ASFormatter& operator=(ASFormatter&); // not to be implemented + template void deleteContainer(T& container); + template void initContainer(T& container, T value); + char peekNextChar() const; + BracketType getBracketType(); + bool adjustChecksumIn(int adjustment); + bool computeChecksumIn(const string& currentLine_); + bool computeChecksumOut(const string& beautifiedLine); + bool addBracketsToStatement(); + bool removeBracketsFromStatement(); + bool commentAndHeaderFollows(); + bool getNextChar(); + bool getNextLine(bool emptyLineWasDeleted = false); + bool isArrayOperator() const; + bool isBeforeComment() const; + bool isBeforeAnyComment() const; + bool isBeforeAnyLineEndComment(int startPos) const; + bool isBeforeMultipleLineEndComments(int startPos) const; + bool isBracketType(BracketType a, BracketType b) const; + bool isClassInitializer() 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 isExternC() const; + bool isNextWordSharpNonParenHeader(int startChar) const; + bool isNonInStatementArrayBracket() const; + bool isOkToSplitFormattedLine(); + bool isPointerOrReference() const; + bool isPointerOrReferenceCentered() const; + bool isPointerOrReferenceVariable(string& word) const; + bool isSharpStyleWithParen(const string* header) const; + bool isStructAccessModified(string& firstLine, size_t index) const; + bool isIndentablePreprocessorBlock(string& firstLine, size_t index); + bool isNDefPreprocStatement(string& firstLine, string& preproc) const; + bool isUnaryOperator() const; + bool isUniformInitializerBracket() const; + bool isImmediatelyPostCast() const; + bool isInExponent() const; + bool isInSwitchStatement() const; + bool isNextCharOpeningBracket(int startChar) const; + bool isOkToBreakBlock(BracketType bracketType) const; + bool isOperatorPaddingDisabled() const; + bool pointerSymbolFollows() const; + int findObjCColonAlignment() const; + int getCurrentLineCommentAdjustment(); + int getNextLineCommentAdjustment(); + int isOneLineBlockReached(string& line, int startChar) const; + void adjustComments(); + void appendChar(char ch, bool canBreakLine); + void appendCharInsideComments(); + void appendOperator(const string& sequence, bool canBreakLine = true); + void appendSequence(const string& sequence, bool canBreakLine = true); + void appendSpacePad(); + void appendSpaceAfter(); + void breakLine(bool isSplitLine = false); + void buildLanguageVectors(); + void updateFormattedLineSplitPoints(char appendedChar); + void updateFormattedLineSplitPointsOperator(const string& sequence); + void checkIfTemplateOpener(); + void clearFormattedLineSplitPoints(); + void convertTabToSpaces(); + void deleteContainer(vector*& container); + void formatArrayRunIn(); + void formatRunIn(); + void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); + void formatClosingBracket(BracketType bracketType); + void formatCommentBody(); + void formatCommentOpener(); + void formatCommentCloser(); + void formatLineCommentBody(); + void formatLineCommentOpener(); + void formatOpeningBracket(BracketType bracketType); + void formatQuoteBody(); + void formatQuoteOpener(); + void formatPointerOrReference(); + void formatPointerOrReferenceCast(); + void formatPointerOrReferenceToMiddle(); + void formatPointerOrReferenceToName(); + void formatPointerOrReferenceToType(); + void fixOptionVariableConflicts(); + void goForward(int i); + void isLineBreakBeforeClosingHeader(); + void initContainer(vector*& container, vector* value); + void initNewLine(); + void padObjCMethodColon(); + void padOperators(const string* newOperator); + void padParens(); + void padParenObjC(void); + void processPreprocessor(); + void resetEndOfStatement(); + void setAttachClosingBracketMode(bool state); + void stripCommentPrefix(); + void testForTimeToSplitFormattedLine(); + void trimContinuationLine(); + void updateFormattedLineSplitPointsPointerOrReference(size_t index); + size_t findFormattedLineSplitPoint() const; + size_t findNextChar(string& line, char searchChar, int searchStart = 0) const; + const string* checkForHeaderFollowingComment(const string& firstLine) const; + const string* getFollowingOperator() const; + string getPreviousWord(const string& line, int currPos) const; + string peekNextText(const string& firstLine, bool endOnEmptyLine = false, bool shouldReset = false) const; - private: // variables - int formatterFileType; - vector* headers; - vector* nonParenHeaders; - vector* preDefinitionHeaders; - vector* preCommandHeaders; - vector* operators; - vector* assignmentOperators; - vector* castOperators; - vector* >* indentableMacros; // for ASEnhancer +private: // variables + int formatterFileType; + vector* headers; + vector* nonParenHeaders; + vector* preDefinitionHeaders; + vector* preCommandHeaders; + vector* operators; + vector* assignmentOperators; + vector* castOperators; + vector* >* indentableMacros; // for ASEnhancer - ASSourceIterator* sourceIterator; - ASEnhancer* enhancer; + ASSourceIterator* sourceIterator; + ASEnhancer* enhancer; - vector* preBracketHeaderStack; - vector* bracketTypeStack; - vector* parenStack; - vector* structStack; - vector* questionMarkStack; + vector* preBracketHeaderStack; + vector* bracketTypeStack; + vector* parenStack; + vector* structStack; + vector* questionMarkStack; - string currentLine; - string formattedLine; - string readyFormattedLine; - string verbatimDelimiter; - const string* currentHeader; - const string* previousOperator; // used ONLY by pad-oper - char currentChar; - char previousChar; - char previousNonWSChar; - char previousCommandChar; - char quoteChar; - streamoff preprocBlockEnd; - int charNum; - int horstmannIndentChars; - int nextLineSpacePadNum; - int preprocBracketTypeStackSize; - int spacePadNum; - int tabIncrementIn; - int templateDepth; - int squareBracketCount; - size_t checksumIn; - size_t checksumOut; - size_t currentLineFirstBracketNum; // first bracket location on currentLine - size_t formattedLineCommentNum; // comment location on formattedLine - size_t leadingSpaces; - size_t maxCodeLength; + string currentLine; + string formattedLine; + string readyFormattedLine; + string verbatimDelimiter; + const string* currentHeader; + const string* previousOperator; // used ONLY by pad-oper + char currentChar; + char previousChar; + char previousNonWSChar; + char previousCommandChar; + char quoteChar; + streamoff preprocBlockEnd; + int charNum; + int horstmannIndentChars; + int nextLineSpacePadNum; + int objCColonAlign; + int preprocBracketTypeStackSize; + int spacePadNum; + int tabIncrementIn; + int templateDepth; + int squareBracketCount; + size_t checksumIn; + size_t checksumOut; + size_t currentLineFirstBracketNum; // first bracket location on currentLine + size_t formattedLineCommentNum; // comment location on formattedLine + size_t leadingSpaces; + size_t maxCodeLength; - // possible split points - size_t maxSemi; // probably a 'for' statement - size_t maxAndOr; // probably an 'if' statement - size_t maxComma; - size_t maxParen; - size_t maxWhiteSpace; - size_t maxSemiPending; - size_t maxAndOrPending; - size_t maxCommaPending; - size_t maxParenPending; - size_t maxWhiteSpacePending; + // possible split points + size_t maxSemi; // probably a 'for' statement + size_t maxAndOr; // probably an 'if' statement + size_t maxComma; + size_t maxParen; + size_t maxWhiteSpace; + size_t maxSemiPending; + size_t maxAndOrPending; + size_t maxCommaPending; + size_t maxParenPending; + size_t maxWhiteSpacePending; - size_t previousReadyFormattedLineLength; - FormatStyle formattingStyle; - BracketMode bracketFormatMode; - BracketType previousBracketType; - PointerAlign pointerAlignment; - ReferenceAlign referenceAlignment; - ObjCColonPad objCColonPadMode; - LineEndFormat lineEnd; - bool isVirgin; - bool shouldPadOperators; - bool shouldPadParensOutside; - bool shouldPadFirstParen; - bool shouldPadParensInside; - bool shouldPadHeader; - bool shouldStripCommentPrefix; - bool shouldUnPadParens; - bool shouldConvertTabs; - bool shouldIndentCol1Comments; - bool shouldIndentPreprocBlock; - bool shouldCloseTemplates; - bool shouldAttachExternC; - bool shouldAttachNamespace; - bool shouldAttachClass; - bool shouldAttachInline; - bool isInLineComment; - bool isInComment; - bool isInCommentStartLine; - bool noTrimCommentContinuation; - bool isInPreprocessor; - bool isInPreprocessorBeautify; - bool isInTemplate; - bool doesLineStartComment; - bool lineEndsInCommentOnly; - bool lineIsCommentOnly; - bool lineIsLineCommentOnly; - bool lineIsEmpty; - bool isImmediatelyPostCommentOnly; - bool isImmediatelyPostEmptyLine; - bool isInClassInitializer; - bool isInQuote; - bool isInVerbatimQuote; - bool haveLineContinuationChar; - bool isInQuoteContinuation; - bool isHeaderInMultiStatementLine; - bool isSpecialChar; - bool isNonParenHeader; - bool foundQuestionMark; - bool foundPreDefinitionHeader; - bool foundNamespaceHeader; - bool foundClassHeader; - bool foundStructHeader; - bool foundInterfaceHeader; - bool foundPreCommandHeader; - bool foundPreCommandMacro; - bool foundCastOperator; - bool isInLineBreak; - bool endOfAsmReached; - bool endOfCodeReached; - bool lineCommentNoIndent; - bool isFormattingModeOff; - bool isInEnum; - bool isInExecSQL; - bool isInAsm; - bool isInAsmOneLine; - bool isInAsmBlock; - bool isLineReady; - bool elseHeaderFollowsComments; - bool caseHeaderFollowsComments; - bool isPreviousBracketBlockRelated; - bool isInPotentialCalculation; - bool isCharImmediatelyPostComment; - bool isPreviousCharPostComment; - bool isCharImmediatelyPostLineComment; - bool isCharImmediatelyPostOpenBlock; - bool isCharImmediatelyPostCloseBlock; - bool isCharImmediatelyPostTemplate; - bool isCharImmediatelyPostReturn; - bool isCharImmediatelyPostThrow; - bool isCharImmediatelyPostOperator; - bool isCharImmediatelyPostPointerOrReference; - bool isInObjCMethodDefinition; - bool isInObjCInterface; - bool isInObjCSelector; - bool breakCurrentOneLineBlock; - bool shouldRemoveNextClosingBracket; - bool isInHorstmannRunIn; - bool currentLineBeginsWithBracket; - bool attachClosingBracketMode; - bool shouldBreakOneLineBlocks; - bool shouldReparseCurrentChar; - bool shouldBreakOneLineStatements; - bool shouldBreakClosingHeaderBrackets; - bool shouldBreakElseIfs; - bool shouldBreakLineAfterLogical; - bool shouldAddBrackets; - bool shouldAddOneLineBrackets; - bool shouldRemoveBrackets; - bool shouldPadMethodColon; - bool shouldPadMethodPrefix; - bool shouldUnPadMethodPrefix; - bool shouldDeleteEmptyLines; - bool needHeaderOpeningBracket; - bool shouldBreakLineAtNextChar; - bool shouldKeepLineUnbroken; - bool passedSemicolon; - bool passedColon; - bool isImmediatelyPostNonInStmt; - bool isCharImmediatelyPostNonInStmt; - bool isImmediatelyPostComment; - bool isImmediatelyPostLineComment; - bool isImmediatelyPostEmptyBlock; - bool isImmediatelyPostPreprocessor; - bool isImmediatelyPostReturn; - bool isImmediatelyPostThrow; - bool isImmediatelyPostOperator; - bool isImmediatelyPostTemplate; - bool isImmediatelyPostPointerOrReference; - bool shouldBreakBlocks; - bool shouldBreakClosingHeaderBlocks; - bool isPrependPostBlockEmptyLineRequested; - bool isAppendPostBlockEmptyLineRequested; - bool isIndentableProprocessor; - bool isIndentableProprocessorBlock; - bool prependEmptyLine; - bool appendOpeningBracket; - bool foundClosingHeader; - bool isInHeader; - bool isImmediatelyPostHeader; - bool isInCase; - bool isFirstPreprocConditional; - bool processedFirstConditional; - bool isJavaStaticConstructor; + size_t previousReadyFormattedLineLength; + FormatStyle formattingStyle; + BracketMode bracketFormatMode; + BracketType previousBracketType; + PointerAlign pointerAlignment; + ReferenceAlign referenceAlignment; + ObjCColonPad objCColonPadMode; + LineEndFormat lineEnd; + bool isVirgin; + bool shouldPadCommas; + bool shouldPadOperators; + bool shouldPadParensOutside; + bool shouldPadFirstParen; + bool shouldPadParensInside; + bool shouldPadHeader; + bool shouldStripCommentPrefix; + bool shouldUnPadParens; + bool shouldConvertTabs; + bool shouldIndentCol1Comments; + bool shouldIndentPreprocBlock; + bool shouldCloseTemplates; + bool shouldAttachExternC; + bool shouldAttachNamespace; + bool shouldAttachClass; + bool shouldAttachInline; + bool isInLineComment; + bool isInComment; + bool isInCommentStartLine; + bool noTrimCommentContinuation; + bool isInPreprocessor; + bool isInPreprocessorBeautify; + bool isInTemplate; + bool doesLineStartComment; + bool lineEndsInCommentOnly; + bool lineIsCommentOnly; + bool lineIsLineCommentOnly; + bool lineIsEmpty; + bool isImmediatelyPostCommentOnly; + bool isImmediatelyPostEmptyLine; + bool isInClassInitializer; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInQuoteContinuation; + bool isHeaderInMultiStatementLine; + bool isSpecialChar; + bool isNonParenHeader; + bool foundQuestionMark; + bool foundPreDefinitionHeader; + bool foundNamespaceHeader; + bool foundClassHeader; + bool foundStructHeader; + bool foundInterfaceHeader; + bool foundPreCommandHeader; + bool foundPreCommandMacro; + bool foundCastOperator; + bool isInLineBreak; + bool endOfAsmReached; + bool endOfCodeReached; + bool lineCommentNoIndent; + bool isFormattingModeOff; + bool isInEnum; + bool isInExecSQL; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isLineReady; + bool elseHeaderFollowsComments; + bool caseHeaderFollowsComments; + bool isPreviousBracketBlockRelated; + bool isInPotentialCalculation; + bool isCharImmediatelyPostComment; + bool isPreviousCharPostComment; + bool isCharImmediatelyPostLineComment; + bool isCharImmediatelyPostOpenBlock; + bool isCharImmediatelyPostCloseBlock; + bool isCharImmediatelyPostTemplate; + bool isCharImmediatelyPostReturn; + bool isCharImmediatelyPostThrow; + bool isCharImmediatelyPostOperator; + bool isCharImmediatelyPostPointerOrReference; + bool isInObjCMethodDefinition; + bool isInObjCInterface; + bool isInObjCReturnType; + bool isInObjCSelector; + bool breakCurrentOneLineBlock; + bool shouldRemoveNextClosingBracket; + bool isInHorstmannRunIn; + bool currentLineBeginsWithBracket; + bool attachClosingBracketMode; + bool shouldBreakOneLineBlocks; + bool shouldReparseCurrentChar; + bool shouldBreakOneLineStatements; + bool shouldBreakClosingHeaderBrackets; + bool shouldBreakElseIfs; + bool shouldBreakLineAfterLogical; + bool shouldAddBrackets; + bool shouldAddOneLineBrackets; + bool shouldRemoveBrackets; + bool shouldPadMethodColon; + bool shouldPadMethodPrefix; + bool shouldUnPadMethodPrefix; + bool shouldPadReturnType; + bool shouldUnPadReturnType; + bool shouldDeleteEmptyLines; + bool needHeaderOpeningBracket; + bool shouldBreakLineAtNextChar; + bool shouldKeepLineUnbroken; + bool passedSemicolon; + bool passedColon; + bool isImmediatelyPostNonInStmt; + bool isCharImmediatelyPostNonInStmt; + bool isImmediatelyPostComment; + bool isImmediatelyPostLineComment; + bool isImmediatelyPostEmptyBlock; + bool isImmediatelyPostObjCMethodPrefix; + bool isImmediatelyPostPreprocessor; + bool isImmediatelyPostReturn; + bool isImmediatelyPostThrow; + bool isImmediatelyPostOperator; + bool isImmediatelyPostTemplate; + bool isImmediatelyPostPointerOrReference; + bool shouldBreakBlocks; + bool shouldBreakClosingHeaderBlocks; + bool isPrependPostBlockEmptyLineRequested; + bool isAppendPostBlockEmptyLineRequested; + bool isIndentableProprocessor; + bool isIndentableProprocessorBlock; + bool prependEmptyLine; + bool appendOpeningBracket; + bool foundClosingHeader; + bool isInHeader; + bool isImmediatelyPostHeader; + bool isInCase; + bool isFirstPreprocConditional; + bool processedFirstConditional; + bool isJavaStaticConstructor; - private: // inline functions - // append the CURRENT character (curentChar) to the current formatted line. - void appendCurrentChar(bool canBreakLine = true) { - appendChar(currentChar, canBreakLine); - } +private: // inline functions + // append the CURRENT character (curentChar) to the current formatted line. + void appendCurrentChar(bool canBreakLine = true) + { + appendChar(currentChar, canBreakLine); + } - // check if a specific sequence exists in the current placement of the current line - bool isSequenceReached(const char* sequence) const { - return currentLine.compare(charNum, strlen(sequence), sequence) == 0; - } + // check if a specific sequence exists in the current placement of the current line + 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_); - } + // call ASBase::findHeader for the current character + 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_); - } + // call ASBase::findOperator for the current character + const string* findOperator(const vector* headers_) + { + return ASBeautifier::findOperator(currentLine, charNum, headers_); + } }; // Class ASFormatter - //----------------------------------------------------------------------------- // astyle namespace global declarations //----------------------------------------------------------------------------- diff --git a/src/astyle_main.cpp b/src/astyle_main.cpp index 999c90a..16a0c4b 100644 --- a/src/astyle_main.cpp +++ b/src/astyle_main.cpp @@ -1,52 +1,37 @@ +// astyle_main.cpp +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * astyle_main.cpp - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * AStyle_main source file map. + * This source file contains several classes. + * They are arranged as follows. + * --------------------------------------- + * namespace astyle { + * ASStreamIterator methods + * ASConsole methods + * // Windows specific + * // Linux specific + * ASLibrary methods + * // Windows specific + * // Linux specific + * ASOptions methods + * Utf8_16 methods + * } // end of astyle namespace + * Global Area --------------------------- + * Java Native Interface functions + * AStyleMainUtf16 entry point + * AStyleMain entry point + * AStyleGetVersion entry point + * main entry point + * --------------------------------------- + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* - AStyle_main source file map. - This source file contains several classes. - They are arranged as follows. - --------------------------------------- - namespace astyle { - ASStreamIterator methods - ASConsole methods - // Windows specific - // Linux specific - ASLibrary methods - // Windows specific - // Linux specific - ASOptions methods - Utf8_16 methods - } // end of astyle namespace - Global Area --------------------------- - Java Native Interface functions - AStyleMainUtf16 entry point - AStyleMain entry point - AStyleGetVersion entry point - main entry point - --------------------------------------- -*/ + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- #include "astyle_main.h" @@ -54,6 +39,7 @@ #include #include #include +#include // needed by some compilers #include // includes for recursive getFileNames() function @@ -74,9 +60,9 @@ #endif /* __VMS */ #endif -#ifdef __DMC__ - #include -#endif +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- // turn off MinGW automatic file globbing // this CANNOT be in the astyle namespace @@ -89,17 +75,17 @@ //---------------------------------------------------------------------------- namespace astyle { - +// // console build variables #ifndef ASTYLE_LIB ASConsole* g_console = NULL; // class to encapsulate console variables ostream* _err = &cerr; // direct error messages to cerr #ifdef _WIN32 char g_fileSeparator = '\\'; // Windows file separator - bool g_isCaseSensitive = false; // Windows IS case sensitive + bool g_isCaseSensitive = false; // Windows IS NOT case sensitive #else char g_fileSeparator = '/'; // Linux file separator - bool g_isCaseSensitive = true; // Linux IS NOT case sensitive + bool g_isCaseSensitive = true; // Linux IS case sensitive #endif // _WIN32 #endif // ASTYLE_LIB @@ -110,7 +96,7 @@ namespace astyle { jmethodID g_mid; #endif -const char* g_version = "2.05.1"; +const char* g_version = "2.06 beta"; //----------------------------------------------------------------------------- // ASStreamIterator class @@ -125,7 +111,6 @@ ASStreamIterator::ASStreamIterator(T* in) eolWindows = 0; eolLinux = 0; eolMacOld = 0; - outputEOL[0] = '\0'; peekStart = 0; prevLineDeleted = false; checkForEmptyLine = false; @@ -227,14 +212,14 @@ string ASStreamIterator::nextLine(bool emptyLineWasDeleted) if (eolWindows >= eolLinux) { if (eolWindows >= eolMacOld) - strcpy(outputEOL, "\r\n"); // Windows (CR+LF) + outputEOL = "\r\n"; // Windows (CR+LF) else - strcpy(outputEOL, "\r"); // MacOld (CR) + outputEOL = "\r"; // MacOld (CR) } else if (eolLinux >= eolMacOld) - strcpy(outputEOL, "\n"); // Linux (LF) + outputEOL = "\n"; // Linux (LF) else - strcpy(outputEOL, "\r"); // MacOld (CR) + outputEOL = "\r"; // MacOld (CR) return buffer; } @@ -339,12 +324,12 @@ bool ASStreamIterator::getLineEndChange(int lineEndFormat) const #ifndef ASTYLE_LIB // rewrite a stringstream converting the line ends -void ASConsole::convertLineEnds(ostringstream &out, int lineEnd) +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 + const string& inStr = out.str(); // avoids strange looking syntax string outStr; // the converted output - int inLength = inStr.length(); + int inLength = (int)inStr.length(); for (int pos = 0; pos < inLength; pos++) { if (inStr[pos] == '\r') @@ -422,14 +407,14 @@ void ASConsole::convertLineEnds(ostringstream &out, int lineEnd) out.str(outStr); } -void ASConsole::correctMixedLineEnds(ostringstream &out) +void ASConsole::correctMixedLineEnds(ostringstream& out) { LineEndFormat lineEndFormat = LINEEND_DEFAULT; - if (strcmp(outputEOL, "\r\n") == 0) + if (outputEOL == "\r\n") lineEndFormat = LINEEND_WINDOWS; - if (strcmp(outputEOL, "\n") == 0) + if (outputEOL == "\n") lineEndFormat = LINEEND_LINUX; - if (strcmp(outputEOL, "\r") == 0) + if (outputEOL == "\r") lineEndFormat = LINEEND_MACOLD; convertLineEnds(out, lineEndFormat); } @@ -493,7 +478,11 @@ void ASConsole::formatCinToCout() ASStreamIterator streamIterator(&outStream); // Windows pipe or redirection always outputs Windows line-ends. // Linux pipe or redirection will output any line end. +#ifdef _WIN32 + LineEndFormat lineEndFormat = LINEEND_DEFAULT; +#else LineEndFormat lineEndFormat = formatter.getLineEndFormat(); +#endif // _WIN32 initializeOutputEOL(lineEndFormat); formatter.init(&streamIterator); @@ -524,7 +513,7 @@ void ASConsole::formatCinToCout() * * @param fileName_ The path and name of the file to be processed. */ -void ASConsole::formatFile(const string &fileName_) +void ASConsole::formatFile(const string& fileName_) { stringstream in; ostringstream out; @@ -721,7 +710,7 @@ bool ASConsole::getPreserveDate() const void ASConsole::setBypassBrowserOpen(bool state) { bypassBrowserOpen = state; } -string ASConsole::getParam(const string &arg, const char* op) +string ASConsole::getParam(const string& arg, const char* op) { return arg.substr(strlen(op)); } @@ -734,21 +723,21 @@ void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat) || lineEndFormat == LINEEND_LINUX || lineEndFormat == LINEEND_MACOLD); - outputEOL[0] = '\0'; // current line end - prevEOL[0] = '\0'; // previous line end + outputEOL.clear(); // current line end + prevEOL.clear(); // previous line end lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only if (lineEndFormat == LINEEND_WINDOWS) - strcpy(outputEOL, "\r\n"); + outputEOL = "\r\n"; else if (lineEndFormat == LINEEND_LINUX) - strcpy(outputEOL, "\n"); + outputEOL = "\n"; else if (lineEndFormat == LINEEND_MACOLD) - strcpy(outputEOL, "\r"); + outputEOL = "\r"; else - outputEOL[0] = '\0'; + outputEOL.clear(); } -FileEncoding ASConsole::readFile(const string &fileName_, stringstream &in) const +FileEncoding ASConsole::readFile(const string& fileName_, stringstream& in) const { const int blockSize = 65536; // 64 KB ifstream fin(fileName_.c_str(), ios::binary); @@ -771,11 +760,11 @@ FileEncoding ASConsole::readFile(const string &fileName_, stringstream &in) cons if (encoding == UTF_16LE || encoding == UTF_16BE) { // convert utf-16 to utf-8 - size_t utf8Size = utf8_16.Utf8LengthFromUtf16(data, dataSize, isBigEndian); + size_t utf8Size = utf8_16.utf8LengthFromUtf16(data, dataSize, isBigEndian); char* utf8Out = new(nothrow) char[utf8Size]; if (!utf8Out) error("Cannot allocate memory for utf-8 conversion", fileName_.c_str()); - size_t utf8Len = utf8_16.Utf16ToUtf8(data, dataSize, isBigEndian, firstBlock, utf8Out); + size_t utf8Len = utf8_16.utf16ToUtf8(data, dataSize, isBigEndian, firstBlock, utf8Out); assert(utf8Len == utf8Size); in << string(utf8Out, utf8Len); delete [] utf8Out; @@ -827,24 +816,24 @@ void ASConsole::setPreserveDate(bool state) { preserveDate = state; } // set outputEOL variable -void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL) +void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const string& currentEOL) { if (lineEndFormat == LINEEND_DEFAULT) { - strcpy(outputEOL, currentEOL); - if (strlen(prevEOL) == 0) - strcpy(prevEOL, outputEOL); - if (strcmp(prevEOL, outputEOL) != 0) + outputEOL = currentEOL; + if (prevEOL.empty()) + prevEOL = outputEOL; + if (prevEOL != outputEOL) { lineEndsMixed = true; filesAreIdentical = false; - strcpy(prevEOL, outputEOL); + prevEOL = outputEOL; } } else { - strcpy(prevEOL, currentEOL); - if (strcmp(prevEOL, outputEOL) != 0) + prevEOL = currentEOL; + if (prevEOL != outputEOL) filesAreIdentical = false; } } @@ -879,7 +868,7 @@ void ASConsole::displayLastError() * * @return The path of the current directory */ -string ASConsole::getCurrentDirectory(const string &fileName_) const +string ASConsole::getCurrentDirectory(const string& fileName_) const { char currdir[MAX_PATH]; currdir[0] = '\0'; @@ -895,7 +884,7 @@ string ASConsole::getCurrentDirectory(const string &fileName_) const * @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) +void ASConsole::getFileNames(const string& directory, const string& wildcard) { vector subDirectory; // sub directories of directory WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile @@ -1083,7 +1072,7 @@ void ASConsole::launchDefaultBrowser(const char* filePathIn /*NULL*/) const * @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 +string ASConsole::getCurrentDirectory(const string& fileName_) const { char* currdir = getenv("PWD"); if (currdir == NULL) @@ -1098,7 +1087,7 @@ string ASConsole::getCurrentDirectory(const string &fileName_) const * @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) +void ASConsole::getFileNames(const string& directory, const string& wildcard) { struct dirent* entry; // entry from readdir() struct stat statbuf; // entry from stat() @@ -1293,9 +1282,9 @@ void ASConsole::launchDefaultBrowser(const char* filePathIn /*NULL*/) const // find xdg-open (usually in /usr/bin) // Mac uses open instead #ifdef __APPLE__ - const char* FILE_OPEN = "open"; + const char* fileOpen = "open"; #else - const char* FILE_OPEN = "xdg-open"; + const char* fileOpen = "xdg-open"; #endif string searchPath; char* searchDir = strtok(paths, ":"); @@ -1305,29 +1294,29 @@ void ASConsole::launchDefaultBrowser(const char* filePathIn /*NULL*/) const if (searchPath.length() > 0 && searchPath[searchPath.length() - 1] != g_fileSeparator) searchPath.append(string(1, g_fileSeparator)); - searchPath.append(FILE_OPEN); + searchPath.append(fileOpen); if (stat(searchPath.c_str(), &statbuf) == 0 && (statbuf.st_mode & S_IFREG)) break; searchDir = strtok(NULL, ":"); } delete[] paths; if (searchDir == NULL) - error(_("Command is not installed"), FILE_OPEN); + error(_("Command is not installed"), fileOpen); // browser open will be bypassed in test programs printf(_("Opening HTML documentation %s\n"), htmlFilePath.c_str()); if (!bypassBrowserOpen) { - execlp(FILE_OPEN, FILE_OPEN, htmlFilePath.c_str(), NULL); + execlp(fileOpen, fileOpen, htmlFilePath.c_str(), NULL); // execlp will NOT return if successful - error(_("Command execute failure"), FILE_OPEN); + error(_("Command execute failure"), fileOpen); } } #endif // _WIN32 // get individual file names from the command-line file path -void ASConsole::getFilePaths(string &filePath) +void ASConsole::getFilePaths(string& filePath) { fileName.clear(); targetDirectory = string(); @@ -1361,7 +1350,8 @@ void ASConsole::getFilePaths(string &filePath) hasWildcard = true; // clear exclude hits vector - for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) + size_t excludeHitsVectorSize = excludeHitsVector.size(); + for (size_t ix = 0; ix < excludeHitsVectorSize; ix++) excludeHitsVector[ix] = false; // If the filename is not quoted on Linux, bash will replace the @@ -1398,7 +1388,7 @@ void ASConsole::getFilePaths(string &filePath) bool excludeErr = false; for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) { - if (excludeHitsVector[ix] == false) + if (!excludeHitsVector[ix]) { excludeErr = true; if (!ignoreExcludeErrorsDisplay) @@ -1441,17 +1431,17 @@ bool ASConsole::fileNameVectorIsEmpty() const return fileNameVector.empty(); } -bool ASConsole::isOption(const string &arg, const char* op) +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) +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 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 @@ -1465,7 +1455,7 @@ bool ASConsole::isParamOption(const string &arg, const char* option) // 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; @@ -1735,6 +1725,9 @@ void ASConsole::printHelp() const cout << " --pad-oper OR -p\n"; cout << " Insert space padding around operators.\n"; cout << endl; + cout << " --pad-comma OR -xg\n"; + cout << " Insert space padding around commas and semicolons.\n"; + cout << endl; cout << " --pad-paren OR -P\n"; cout << " Insert space padding around parenthesis on both the outside\n"; cout << " and the inside.\n"; @@ -1836,9 +1829,6 @@ void ASConsole::printHelp() const cout << endl; cout << "Objective-C Options:\n"; cout << "--------------------\n"; - cout << " --align-method-colon OR -xM\n"; - cout << " Align the colons in an Objective-C method definition.\n"; - cout << endl; cout << " --pad-method-prefix OR -xQ\n"; cout << " Insert space padding after the '-' or '+' Objective-C\n"; cout << " method prefix.\n"; @@ -1847,6 +1837,15 @@ void ASConsole::printHelp() const cout << " Remove all space padding after the '-' or '+' Objective-C\n"; cout << " method prefix.\n"; cout << endl; + cout << " --pad-return-type OR -xq\n"; + cout << " Insert space padding after the Objective-C return type.\n"; + cout << endl; + cout << " --unpad-return-type OR -xr\n"; + cout << " Remove all space padding after the Objective-C return type.\n"; + cout << endl; + cout << " --align-method-colon OR -xM\n"; + cout << " Align the colons in an Objective-C method definition.\n"; + cout << endl; cout << " --pad-method-colon=none OR -xP\n"; cout << " --pad-method-colon=all OR -xP1\n"; cout << " --pad-method-colon=after OR -xP2\n"; @@ -1960,7 +1959,7 @@ void ASConsole::processFiles() // process options from the command line and options file // build the vectors fileNameVector, excludeVector, optionsVector, and fileOptionsVector -void ASConsole::processOptions(vector &argvOptions) +void ASConsole::processOptions(vector& argvOptions) { string arg; bool ok = true; @@ -1986,7 +1985,7 @@ void ASConsole::processOptions(vector &argvOptions) { optionsFileName = getParam(arg, "--options="); optionsFileRequired = true; - if (optionsFileName.compare("") == 0) + if (optionsFileName.empty()) setOptionsFileName(" "); } else if ( isOption(arg, "-h") @@ -2028,31 +2027,31 @@ void ASConsole::processOptions(vector &argvOptions) // get options file path and name if (shouldParseOptionsFile) { - if (optionsFileName.compare("") == 0) + if (optionsFileName.empty()) { char* env = getenv("ARTISTIC_STYLE_OPTIONS"); if (env != NULL) setOptionsFileName(env); } - if (optionsFileName.compare("") == 0) + if (optionsFileName.empty()) { char* env = getenv("HOME"); if (env != NULL) setOptionsFileName(string(env) + "/.astylerc"); } - if (optionsFileName.compare("") == 0) + if (optionsFileName.empty()) { char* env = getenv("USERPROFILE"); if (env != NULL) setOptionsFileName(string(env) + "/astylerc"); } - if (optionsFileName.compare("") != 0) + if (!optionsFileName.empty()) standardizePath(optionsFileName); } // create the options file vector and parse the options for errors ASOptions options(formatter); - if (optionsFileName.compare("") != 0) + if (!optionsFileName.empty()) { ifstream optionsIn(optionsFileName.c_str()); if (optionsIn) @@ -2126,7 +2125,7 @@ void ASConsole::renameFile(const char* oldFileName, const char* newFileName, con // 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 +void ASConsole::standardizePath(string& path, bool removeBeginningSeparator /*false*/) const { #ifdef __VMS struct FAB fab; @@ -2187,7 +2186,7 @@ void ASConsole::standardizePath(string &path, bool removeBeginningSeparator /*fa path.erase(0, 1); } -void ASConsole::printMsg(const char* msg, const string &data) const +void ASConsole::printMsg(const char* msg, const string& data) const { if (isQuiet) return; @@ -2208,14 +2207,19 @@ void ASConsole::printVerboseHeader() const if (isQuiet) return; // get the date - struct tm* ptr; time_t lt; char str[20]; lt = time(NULL); - ptr = localtime(<); + struct tm* ptr = localtime(<); strftime(str, 20, "%x", ptr); // print the header - printf("Artistic Style %s %s\n", g_version, str); + // 60 is the length of the separator in printSeparatingLine() + string header = "Artistic Style " + string(g_version); + size_t numSpaces = 60 - header.length() - strlen(str); + header.append(numSpaces, ' '); + header.append(str); + header.append("\n"); + printf("%s", header.c_str()); // print options file if (!optionsFileName.empty()) printf(_("Using default options file %s\n"), optionsFileName.c_str()); @@ -2265,7 +2269,7 @@ void ASConsole::sleep(int seconds) const while (clock() < endwait) {} } -bool ASConsole::stringEndsWith(const string &str, const string &suffix) const +bool ASConsole::stringEndsWith(const string& str, const string& suffix) const { int strIndex = (int) str.length() - 1; int suffixIndex = (int) suffix.length() - 1; @@ -2367,7 +2371,7 @@ int ASConsole::wildcmp(const char* wild, const char* data) const return !*wild; } -void ASConsole::writeFile(const string &fileName_, FileEncoding encoding, ostringstream &out) const +void ASConsole::writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const { // save date accessed and date modified of original file struct stat stBuf; @@ -2391,9 +2395,9 @@ void ASConsole::writeFile(const string &fileName_, FileEncoding encoding, ostrin { // convert utf-8 to utf-16 bool isBigEndian = (encoding == UTF_16BE); - size_t utf16Size = utf8_16.Utf16LengthFromUtf8(out.str().c_str(), out.str().length()); + size_t utf16Size = utf8_16.utf16LengthFromUtf8(out.str().c_str(), out.str().length()); char* utf16Out = new char[utf16Size]; - size_t utf16Len = utf8_16.Utf8ToUtf16(const_cast(out.str().c_str()), + size_t utf16Len = utf8_16.utf8ToUtf16(const_cast(out.str().c_str()), out.str().length(), isBigEndian, utf16Out); assert(utf16Len == utf16Size); fout << string(utf16Out, utf16Len); @@ -2426,13 +2430,13 @@ void ASConsole::writeFile(const string &fileName_, FileEncoding encoding, ostrin } } +#else // ASTYLE_LIB + //----------------------------------------------------------------------------- // ASLibrary class // used by shared object (DLL) calls //----------------------------------------------------------------------------- -#else // ASTYLE_LIB - utf16_t* ASLibrary::formatUtf16(const utf16_t* pSourceIn, // the source to be formatted const utf16_t* pOptions, // AStyle options fpError fpErrorHandler, // error handler function @@ -2498,14 +2502,14 @@ utf16_t* ASLibrary::convertUtf8ToUtf16(const char* utf8In, fpAlloc fpMemoryAlloc size_t dataSize = strlen(utf8In); bool isBigEndian = utf8_16.getBigEndian(); // return size is in number of CHARs, not utf16_t - size_t utf16Size = (utf8_16.Utf16LengthFromUtf8(data, dataSize) + sizeof(utf16_t)); - char* utf16Out = fpMemoryAlloc(utf16Size); + size_t utf16Size = (utf8_16.utf16LengthFromUtf8(data, dataSize) + sizeof(utf16_t)); + char* utf16Out = fpMemoryAlloc((long)utf16Size); if (utf16Out == NULL) return NULL; #ifdef NDEBUG - utf8_16.Utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); + utf8_16.utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); #else - size_t utf16Len = utf8_16.Utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); + size_t utf16Len = utf8_16.utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); assert(utf16Len == utf16Size); #endif assert(utf16Size == (utf8_16.utf16len(reinterpret_cast(utf16Out)) + 1) * sizeof(utf16_t)); @@ -2525,14 +2529,14 @@ char* ASLibrary::convertUtf16ToUtf8(const utf16_t* utf16In) const // size must be in chars size_t dataSize = utf8_16.utf16len(utf16In) * sizeof(utf16_t); bool isBigEndian = utf8_16.getBigEndian(); - size_t utf8Size = utf8_16.Utf8LengthFromUtf16(data, dataSize, isBigEndian) + 1; + size_t utf8Size = utf8_16.utf8LengthFromUtf16(data, dataSize, isBigEndian) + 1; char* utf8Out = new(nothrow) char[utf8Size]; if (utf8Out == NULL) return NULL; #ifdef NDEBUG - utf8_16.Utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); + utf8_16.utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); #else - size_t utf8Len = utf8_16.Utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); + size_t utf8Len = utf8_16.utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); assert(utf8Len == utf8Size); #endif assert(utf8Size == strlen(utf8Out) + 1); @@ -2552,7 +2556,7 @@ char* ASLibrary::convertUtf16ToUtf8(const utf16_t* utf16In) const * * @return true if no errors, false if errors */ -bool ASOptions::parseOptions(vector &optionsVector, const string &errorInfo) +bool ASOptions::parseOptions(vector& optionsVector, const string& errorInfo) { vector::iterator option; string arg, subArg; @@ -2596,7 +2600,7 @@ bool ASOptions::parseOptions(vector &optionsVector, const string &errorI return true; } -void ASOptions::parseOption(const string &arg, const string &errorInfo) +void ASOptions::parseOption(const string& arg, const string& errorInfo) { if ( isOption(arg, "style=allman") || isOption(arg, "style=bsd") || isOption(arg, "style=break") ) { @@ -2618,7 +2622,7 @@ void ASOptions::parseOption(const string &arg, const string &errorInfo) { formatter.setFormattingStyle(STYLE_WHITESMITH); } - else if (isOption(arg, "style=vtk")) + else if ( isOption(arg, "style=vtk") ) { formatter.setFormattingStyle(STYLE_VTK); } @@ -2876,6 +2880,10 @@ void ASOptions::parseOption(const string &arg, const string &errorInfo) { formatter.setOperatorPaddingMode(true); } + else if (isOption(arg, "xg", "pad-comma")) + { + formatter.setCommaPaddingMode(true); + } else if ( isOption(arg, "xe", "delete-empty-lines") ) { formatter.setDeleteEmptyLinesMode(true); @@ -3030,10 +3038,6 @@ void ASOptions::parseOption(const string &arg, const string &errorInfo) formatter.setStripCommentPrefix(true); } // Objective-C options - else if ( isOption(arg, "xM", "align-method-colon") ) - { - formatter.setAlignMethodColon(true); - } else if ( isOption(arg, "xQ", "pad-method-prefix") ) { formatter.setMethodPrefixPaddingMode(true); @@ -3042,6 +3046,18 @@ void ASOptions::parseOption(const string &arg, const string &errorInfo) { formatter.setMethodPrefixUnPaddingMode(true); } + else if (isOption(arg, "xq", "pad-return-type")) + { + formatter.setReturnTypePaddingMode(true); + } + else if (isOption(arg, "xr", "unpad-return-type")) + { + formatter.setReturnTypeUnPaddingMode(true); + } + else if (isOption(arg, "xM", "align-method-colon")) + { + formatter.setAlignMethodColon(true); + } else if ( isOption(arg, "xP0", "pad-method-colon=none") ) { formatter.setObjCColonPaddingMode(COLON_PAD_NONE); @@ -3182,7 +3198,7 @@ void ASOptions::parseOption(const string &arg, const string &errorInfo) } // End of parseOption function // Parse options from the options file. -void ASOptions::importOptions(istream &in, vector &optionsVector) +void ASOptions::importOptions(istream& in, vector& optionsVector) { char ch; bool isInQuote = false; @@ -3235,34 +3251,34 @@ string ASOptions::getOptionErrors() const return optionErrors.str(); } -string ASOptions::getParam(const string &arg, const char* op) +string ASOptions::getParam(const string& arg, const char* op) { return arg.substr(strlen(op)); } -string ASOptions::getParam(const string &arg, const char* op1, const char* op2) +string ASOptions::getParam(const string& arg, const char* op1, const char* op2) { return isParamOption(arg, op1) ? getParam(arg, op1) : getParam(arg, op2); } -bool ASOptions::isOption(const string &arg, const char* op) +bool ASOptions::isOption(const string& arg, const char* op) { return arg.compare(op) == 0; } -bool ASOptions::isOption(const string &arg, const char* op1, const char* op2) +bool ASOptions::isOption(const string& arg, const char* op1, const char* op2) { return (isOption(arg, op1) || isOption(arg, op2)); } -void ASOptions::isOptionError(const string &arg, const string &errorInfo) +void ASOptions::isOptionError(const string& arg, const string& errorInfo) { if (optionErrors.str().length() == 0) optionErrors << errorInfo << endl; // need main error message optionErrors << arg << endl; } -bool ASOptions::isParamOption(const string &arg, const char* option) +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 @@ -3272,7 +3288,7 @@ bool ASOptions::isParamOption(const string &arg, const char* option) return retVal; } -bool ASOptions::isParamOption(const string &arg, const char* option1, const char* option2) +bool ASOptions::isParamOption(const string& arg, const char* option1, const char* option2) { return isParamOption(arg, option1) || isParamOption(arg, option2); } @@ -3310,7 +3326,7 @@ size_t Utf8_16::utf16len(const utf16* utf16In) const // Modified for Artistic Style by Jim Pattee. // Compute the length of an output utf-8 file given a utf-16 file. // Input inLen is the size in BYTES (not wchar_t). -size_t Utf8_16::Utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const +size_t Utf8_16::utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const { size_t len = 0; size_t wcharLen = inLen / 2; @@ -3338,7 +3354,7 @@ size_t Utf8_16::Utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBi // Copyright (C) 2002 Scott Kirkwood. // Modified for Artistic Style by Jim Pattee. // Convert a utf-8 file to utf-16. -size_t Utf8_16::Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const +size_t Utf8_16::utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const { int nCur = 0; ubyte* pRead = reinterpret_cast(utf8In); @@ -3352,40 +3368,41 @@ size_t Utf8_16::Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* { switch (state) { - case eStart: - if ((0xF0 & *pRead) == 0xF0) - { - nCur = (0x7 & *pRead) << 18; - state = eSecondOf4Bytes; - } - else if ((0xE0 & *pRead) == 0xE0) - { - nCur = (~0xE0 & *pRead) << 12; + case eStart: + if ((0xF0 & *pRead) == 0xF0) + { + nCur = (0x7 & *pRead) << 18; + state = eSecondOf4Bytes; + } + else if ((0xE0 & *pRead) == 0xE0) + { + nCur = (~0xE0 & *pRead) << 12; + state = ePenultimate; + } + else if ((0xC0 & *pRead) == 0xC0) + { + nCur = (~0xC0 & *pRead) << 6; + state = eFinal; + } + else + { + nCur = *pRead; + state = eStart; + } + break; + case eSecondOf4Bytes: + nCur |= (0x3F & *pRead) << 12; state = ePenultimate; - } - else if ((0xC0 & *pRead) == 0xC0) - { - nCur = (~0xC0 & *pRead) << 6; + break; + case ePenultimate: + nCur |= (0x3F & *pRead) << 6; state = eFinal; - } - else - { - nCur = *pRead; + break; + case eFinal: + nCur |= (0x3F & *pRead); state = eStart; - } - break; - case eSecondOf4Bytes: - nCur |= (0x3F & *pRead) << 12; - state = ePenultimate; - break; - case ePenultimate: - nCur |= (0x3F & *pRead) << 6; - state = eFinal; - break; - case eFinal: - nCur |= (0x3F & *pRead); - state = eStart; - break; + break; + // no default case is needed } ++pRead; @@ -3413,7 +3430,7 @@ size_t Utf8_16::Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* // Modified for Artistic Style by Jim Pattee. // Compute the length of an output utf-16 file given a utf-8 file. // Return value is the size in BYTES (not wchar_t). -size_t Utf8_16::Utf16LengthFromUtf8(const char* utf8In, size_t len) const +size_t Utf8_16::utf16LengthFromUtf8(const char* utf8In, size_t len) const { size_t ulen = 0; size_t charLen; @@ -3442,7 +3459,7 @@ size_t Utf8_16::Utf16LengthFromUtf8(const char* utf8In, size_t len) const // Copyright (C) 2002 Scott Kirkwood. // Modified for Artistic Style by Jim Pattee. // Convert a utf-16 file to utf-8. -size_t Utf8_16::Utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, +size_t Utf8_16::utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, bool firstBlock, char* utf8Out) const { int nCur16 = 0; @@ -3460,73 +3477,74 @@ size_t Utf8_16::Utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, { switch (state) { - case eStart: - if (pRead >= pEnd) - { - ++pRead; - break; - } - if (isBigEndian) - { - nCur16 = static_cast(*pRead++ << 8); - nCur16 |= static_cast(*pRead); - } - else - { - nCur16 = *pRead++; - nCur16 |= static_cast(*pRead << 8); - } - if (nCur16 >= SURROGATE_LEAD_FIRST && nCur16 <= SURROGATE_LEAD_LAST) - { - ++pRead; - int trail; + case eStart: + if (pRead >= pEnd) + { + ++pRead; + break; + } if (isBigEndian) { - trail = static_cast(*pRead++ << 8); - trail |= static_cast(*pRead); + nCur16 = static_cast(*pRead++ << 8); + nCur16 |= static_cast(*pRead); } else { - trail = *pRead++; - trail |= static_cast(*pRead << 8); + nCur16 = *pRead++; + nCur16 |= static_cast(*pRead << 8); } - nCur16 = (((nCur16 & 0x3ff) << 10) | (trail & 0x3ff)) + SURROGATE_FIRST_VALUE; - } - ++pRead; + if (nCur16 >= SURROGATE_LEAD_FIRST && nCur16 <= SURROGATE_LEAD_LAST) + { + ++pRead; + int trail; + if (isBigEndian) + { + trail = static_cast(*pRead++ << 8); + trail |= static_cast(*pRead); + } + else + { + trail = *pRead++; + trail |= static_cast(*pRead << 8); + } + nCur16 = (((nCur16 & 0x3ff) << 10) | (trail & 0x3ff)) + SURROGATE_FIRST_VALUE; + } + ++pRead; - if (nCur16 < 0x80) - { - nCur = static_cast(nCur16 & 0xFF); - state = eStart; - } - else if (nCur16 < 0x800) - { - nCur = static_cast(0xC0 | (nCur16 >> 6)); - state = eFinal; - } - else if (nCur16 < SURROGATE_FIRST_VALUE) - { - nCur = static_cast(0xE0 | (nCur16 >> 12)); + if (nCur16 < 0x80) + { + nCur = static_cast(nCur16 & 0xFF); + state = eStart; + } + else if (nCur16 < 0x800) + { + nCur = static_cast(0xC0 | (nCur16 >> 6)); + state = eFinal; + } + else if (nCur16 < SURROGATE_FIRST_VALUE) + { + nCur = static_cast(0xE0 | (nCur16 >> 12)); + state = ePenultimate; + } + else + { + nCur = static_cast(0xF0 | (nCur16 >> 18)); + state = eSecondOf4Bytes; + } + break; + case eSecondOf4Bytes: + nCur = static_cast(0x80 | ((nCur16 >> 12) & 0x3F)); state = ePenultimate; - } - else - { - nCur = static_cast(0xF0 | (nCur16 >> 18)); - state = eSecondOf4Bytes; - } - break; - case eSecondOf4Bytes: - nCur = static_cast(0x80 | ((nCur16 >> 12) & 0x3F)); - state = ePenultimate; - break; - case ePenultimate: - nCur = static_cast(0x80 | ((nCur16 >> 6) & 0x3F)); - state = eFinal; - break; - case eFinal: - nCur = static_cast(0x80 | (nCur16 & 0x3F)); - state = eStart; - break; + break; + case ePenultimate: + nCur = static_cast(0x80 | ((nCur16 >> 6) & 0x3F)); + state = eFinal; + break; + case eFinal: + nCur = static_cast(0x80 | (nCur16 & 0x3F)); + state = eStart; + break; + // no default case is needed } *pCur++ = static_cast(nCur); } @@ -3610,14 +3628,25 @@ char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded) char* buffer = new(nothrow) char[memoryNeeded]; return buffer; } + #endif // ASTYLE_JNI //---------------------------------------------------------------------------- -// Entry point for AStyleMainUtf16 library builds +// ASTYLE_LIB functions for library builds //---------------------------------------------------------------------------- #ifdef ASTYLE_LIB +//---------------------------------------------------------------------------- +// ASTYLE_LIB entry point for AStyleMainUtf16 library builds +//---------------------------------------------------------------------------- +/* +* IMPORTANT Visual C DLL linker for WIN32 must have the additional options: +* /EXPORT:AStyleMain=_AStyleMain@16 +* /EXPORT:AStyleMainUtf16=_AStyleMainUtf16@16 +* /EXPORT:AStyleGetVersion=_AStyleGetVersion@0 +* No /EXPORT is required for x64 +*/ extern "C" EXPORT utf16_t* STDCALL AStyleMainUtf16(const utf16_t* pSourceIn, // the source to be formatted const utf16_t* pOptions, // AStyle options fpError fpErrorHandler, // error handler function @@ -3660,8 +3689,10 @@ extern "C" EXPORT utf16_t* STDCALL AStyleMainUtf16(const utf16_t* pSourceIn, // // ASTYLE_LIB entry point for library builds //---------------------------------------------------------------------------- /* - * IMPORTANT VC DLL linker for WIN32 must have the parameter /EXPORT:AStyleMain=_AStyleMain@16 - * /EXPORT:AStyleGetVersion=_AStyleGetVersion@0 + * IMPORTANT Visual C DLL linker for WIN32 must have the additional options: + * /EXPORT:AStyleMain=_AStyleMain@16 + * /EXPORT:AStyleMainUtf16=_AStyleMainUtf16@16 + * /EXPORT:AStyleGetVersion=_AStyleGetVersion@0 * No /EXPORT is required for x64 */ extern "C" EXPORT char* STDCALL AStyleMain(const char* pSourceIn, // the source to be formatted @@ -3721,8 +3752,8 @@ extern "C" EXPORT char* STDCALL AStyleMain(const char* pSourceIn, // the source } } - unsigned long textSizeOut = out.str().length(); - char* pTextOut = fpMemoryAlloc(textSizeOut + 1); // call memory allocation function + size_t textSizeOut = out.str().length(); + char* pTextOut = fpMemoryAlloc((long)textSizeOut + 1); // call memory allocation function if (pTextOut == NULL) { fpErrorHandler(120, "Allocation failure on output."); diff --git a/src/astyle_main.h b/src/astyle_main.h index f58ca66..bfbc0e2 100644 --- a/src/astyle_main.h +++ b/src/astyle_main.h @@ -1,28 +1,7 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * astyle_main.h - * - * Copyright (C) 2014 by Jim Pattee - * - * - * This file is a part of Artistic Style - an indentation and - * reformatting tool for C, C++, C# and Java source files. - * - * - * 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. - * - * Artistic Style is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Artistic Style. If not, see . - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - */ +// astyle_main.h +// Copyright (c) 2016 by Jim Pattee . +// This code is licensed under the MIT License. +// License.txt describes the conditions under which this software may be distributed. #ifndef ASTYLE_MAIN_H #define ASTYLE_MAIN_H @@ -64,27 +43,38 @@ #define _(a) localizer.settext(a) #endif // ASTYLE_LIB +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- + // for G++ implementation of string.compare: #if defined(__GNUC__) && __GNUC__ < 3 #error - Use GNU C compiler release 3 or higher #endif +// for getenv and localtime +#if defined(_MSC_VER) + #pragma warning(disable: 4996) // secure version deprecation warnings +#endif + // for namespace problem in version 5.0 #if defined(_MSC_VER) && _MSC_VER < 1200 // check for V6.0 #error - Use Microsoft compiler version 6 or higher #endif +#ifdef __clang__ + #pragma clang diagnostic ignored "-Wdeprecated-declarations" // getenv, localtime + #pragma clang diagnostic ignored "-Wmissing-braces" +#endif + // for mingw BOM, UTF-16, and Unicode functions #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) - #if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 16)) + #if (__MINGW32_MAJOR_VERSION > 3) || \ + ((__MINGW32_MAJOR_VERSION == 3)&& (__MINGW32_MINOR_VERSION < 16)) #error - Use MinGW compiler version 4 or higher #endif #endif -//---------------------------------------------------------------------------- -// definitions -//---------------------------------------------------------------------------- - #ifdef ASTYLE_LIB // define STDCALL and EXPORT for Windows @@ -124,7 +114,7 @@ //---------------------------------------------------------------------------- namespace astyle { - +// //---------------------------------------------------------------------------- // ASStreamIterator class // typename will be istringstream for GUI and istream otherwise @@ -134,39 +124,39 @@ namespace astyle { template class ASStreamIterator : public ASSourceIterator { - public: - bool checkForEmptyLine; +public: + bool checkForEmptyLine; - // function declarations - ASStreamIterator(T* in); - virtual ~ASStreamIterator(); - bool getLineEndChange(int lineEndFormat) const; - int getStreamLength() const; - string nextLine(bool emptyLineWasDeleted); - string peekNextLine(); - void peekReset(); - void saveLastInputLine(); - streamoff tellg(); + // function declarations + explicit ASStreamIterator(T* in); + virtual ~ASStreamIterator(); + bool getLineEndChange(int lineEndFormat) const; + int getStreamLength() const; + string nextLine(bool emptyLineWasDeleted); + string peekNextLine(); + void peekReset(); + void saveLastInputLine(); + streamoff tellg(); - private: - ASStreamIterator(const ASStreamIterator ©); // copy constructor not to be implemented - 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 - int eolLinux; // number of Linux line endings, LF - int eolMacOld; // number of old Mac line endings. CR - char outputEOL[4]; // next output end of line char - streamoff streamLength; // length of the input file stream - streamoff peekStart; // starting position for peekNextLine - bool prevLineDeleted; // the previous input line was deleted +private: + ASStreamIterator(const ASStreamIterator& copy); // copy constructor not to be implemented + 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 + string outputEOL; // next output end of line char + int eolWindows; // number of Windows line endings, CRLF + int eolLinux; // number of Linux line endings, LF + int eolMacOld; // number of old Mac line endings. CR + streamoff streamLength; // length of the input file stream + streamoff peekStart; // starting position for peekNextLine + bool prevLineDeleted; // the previous input line was deleted - public: // inline functions - bool compareToInputBuffer(const string &nextLine_) const - { return (nextLine_ == prevBuffer); } - const char* getOutputEOL() const { return outputEOL; } - bool hasMoreLines() const { return !inStream->eof(); } +public: // inline functions + bool compareToInputBuffer(const string& nextLine_) const + { return (nextLine_ == prevBuffer); } + const string& getOutputEOL() const { return outputEOL; } + bool hasMoreLines() const { return !inStream->eof(); } }; //---------------------------------------------------------------------------- @@ -175,26 +165,26 @@ class ASStreamIterator : public ASSourceIterator class Utf8_16 { - private: - typedef unsigned short utf16; // 16 bits - typedef unsigned char utf8; // 8 bits - typedef unsigned char ubyte; // 8 bits - enum { SURROGATE_LEAD_FIRST = 0xD800 }; - enum { SURROGATE_LEAD_LAST = 0xDBFF }; - enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; - enum { SURROGATE_TRAIL_LAST = 0xDFFF }; - enum { SURROGATE_FIRST_VALUE = 0x10000 }; - enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; +private: + typedef unsigned short utf16; // 16 bits + typedef unsigned char utf8; // 8 bits + typedef unsigned char ubyte; // 8 bits + enum { SURROGATE_LEAD_FIRST = 0xD800 }; + enum { SURROGATE_LEAD_LAST = 0xDBFF }; + enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; + enum { SURROGATE_TRAIL_LAST = 0xDFFF }; + enum { SURROGATE_FIRST_VALUE = 0x10000 }; + enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; - public: - bool getBigEndian() const; - int swap16bit(int value) const; - size_t utf16len(const utf16* utf16In) const; - size_t Utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const; - size_t Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const; - size_t Utf16LengthFromUtf8(const char* utf8In, size_t inLen) const; - size_t Utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, - bool firstBlock, char* utf8Out) const; +public: + bool getBigEndian() const; + int swap16bit(int value) const; + size_t utf16len(const utf16* utf16In) const; + size_t utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const; + size_t utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const; + size_t utf16LengthFromUtf8(const char* utf8In, size_t inLen) const; + size_t utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, + bool firstBlock, char* utf8Out) const; }; //---------------------------------------------------------------------------- @@ -204,27 +194,28 @@ class Utf8_16 class ASOptions { - public: - ASOptions(ASFormatter &formatterArg) : formatter(formatterArg) {} - string getOptionErrors() const; - void importOptions(istream &in, vector &optionsVector); - bool parseOptions(vector &optionsVector, const string &errorInfo); +public: + explicit ASOptions(ASFormatter& formatterArg) : formatter(formatterArg) {} + string getOptionErrors() const; + 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 +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); + // functions + ASOptions(const ASOptions&); // copy constructor not to be implemented + ASOptions& operator=(ASOptions&); // assignment operator 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); }; #ifndef ASTYLE_LIB @@ -235,153 +226,152 @@ class ASOptions class ASConsole { - private: // variables - ASFormatter &formatter; // reference to the ASFormatter object - ASLocalizer localizer; // ASLocalizer object +private: // variables + ASFormatter& formatter; // reference to the ASFormatter object + ASLocalizer localizer; // ASLocalizer object + // command line options + bool isRecursive; // recursive option + bool isDryRun; // dry-run option + bool noBackup; // suffix=none option + bool preserveDate; // preserve-date option + bool isVerbose; // verbose option + bool isQuiet; // quiet option + bool isFormattedOnly; // formatted lines only option + bool ignoreExcludeErrors; // don't abort on unmatched excludes + bool ignoreExcludeErrorsDisplay; // don't display unmatched excludes + bool optionsFileRequired; // options= option + bool useAscii; // ascii option + // other variables + bool bypassBrowserOpen; // don't open the browser on html options + 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 + int filesFormatted; // number of files formatted + int filesUnchanged; // number of files unchanged + bool lineEndsMixed; // output has mixed line ends + int linesOut; // number of output lines + + Utf8_16 utf8_16; // utf8/16 conversion methods + + string outputEOL; // current line end + string prevEOL; // previous line end + string optionsFileName; // file path and name of the options file to use + string origSuffix; // suffix= option + string targetDirectory; // path to the directory being processed + string targetFilename; // file name being processed + + vector excludeVector; // exclude from wildcard hits + vector excludeHitsVector; // exclude flags for error reporting + vector fileNameVector; // file paths and names from the command line + vector optionsVector; // options from the command line + vector fileOptionsVector; // options from the options file + vector fileName; // files to be processed including path + +public: // variables + explicit ASConsole(ASFormatter& formatterArg) : formatter(formatterArg) + { // command line options - bool isRecursive; // recursive option - bool isDryRun; // dry-run option - bool noBackup; // suffix=none option - bool preserveDate; // preserve-date option - bool isVerbose; // verbose option - bool isQuiet; // quiet option - bool isFormattedOnly; // formatted lines only option - bool ignoreExcludeErrors; // don't abort on unmatched excludes - bool ignoreExcludeErrorsDisplay; // don't display unmatched excludes - bool optionsFileRequired; // options= option - bool useAscii; // ascii option + isRecursive = false; + isDryRun = false; + noBackup = false; + preserveDate = false; + isVerbose = false; + isQuiet = false; + isFormattedOnly = false; + ignoreExcludeErrors = false; + ignoreExcludeErrorsDisplay = false; + optionsFileRequired = false; + useAscii = false; // other variables - bool bypassBrowserOpen; // don't open the browser on html options - 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 - int filesFormatted; // number of files formatted - int filesUnchanged; // number of files unchanged - bool lineEndsMixed; // output has mixed line ends - int linesOut; // number of output lines - char outputEOL[4]; // current line end - char prevEOL[4]; // previous line end + bypassBrowserOpen = false; + hasWildcard = false; + filesAreIdentical = true; + lineEndsMixed = false; + origSuffix = ".orig"; + mainDirectoryLength = 0; + filesFormatted = 0; + filesUnchanged = 0; + linesOut = 0; + } - Utf8_16 utf8_16; // utf8/16 conversion methods +public: // functions + void convertLineEnds(ostringstream& out, int lineEnd); + FileEncoding detectEncoding(const char* data, size_t dataSize) const; + void error() const; + void error(const char* why, const char* what) const; + void formatCinToCout(); + vector getArgvOptions(int argc, char** argv) const; + bool fileNameVectorIsEmpty() const; + bool getFilesAreIdentical() const; + int getFilesFormatted() const; + bool getIgnoreExcludeErrors() const; + bool getIgnoreExcludeErrorsDisplay() const; + bool getIsDryRun() const; + bool getIsFormattedOnly() const; + bool getIsQuiet() const; + bool getIsRecursive() const; + bool getIsVerbose() const; + bool getLineEndsMixed() const; + bool getNoBackup() const; + bool getPreserveDate() const; + string getLanguageID() const; + string getNumberFormat(int num, size_t = 0) const; + string getNumberFormat(int num, const char* groupingArg, const char* separator) const; + string getOptionsFileName() const; + string getOrigSuffix() const; + void processFiles(); + void processOptions(vector& argvOptions); + void setBypassBrowserOpen(bool state); + void setIgnoreExcludeErrors(bool state); + void setIgnoreExcludeErrorsAndDisplay(bool state); + void setIsDryRun(bool state); + void setIsFormattedOnly(bool state); + void setIsQuiet(bool state); + void setIsRecursive(bool state); + void setIsVerbose(bool state); + void setNoBackup(bool state); + void setOptionsFileName(string name); + 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 updateExcludeVector(string suffixParam); + vector getExcludeVector() const; + vector getExcludeHitsVector() const; + vector getFileNameVector() const; + vector getOptionsVector() const; + vector getFileOptionsVector() const; + vector getFileName() const; - string optionsFileName; // file path and name of the options file to use - string origSuffix; // suffix= option - string targetDirectory; // path to the directory being processed - string targetFilename; // file name being processed - - vector excludeVector; // exclude from wildcard hits - vector excludeHitsVector; // exclude flags for error reporting - vector fileNameVector; // file paths and names from the command line - vector optionsVector; // options from the command line - vector fileOptionsVector; // options from the options file - vector fileName; // files to be processed including path - - public: // variables - ASConsole(ASFormatter &formatterArg) : formatter(formatterArg) { - // command line options - isRecursive = false; - isDryRun = false; - noBackup = false; - preserveDate = false; - isVerbose = false; - isQuiet = false; - isFormattedOnly = false; - ignoreExcludeErrors = false; - ignoreExcludeErrorsDisplay = false; - optionsFileRequired = false; - useAscii = false; - // other variables - bypassBrowserOpen = false; - hasWildcard = false; - filesAreIdentical = true; - lineEndsMixed = false; - outputEOL[0] = '\0'; - prevEOL[0] = '\0'; - origSuffix = ".orig"; - mainDirectoryLength = 0; - filesFormatted = 0; - filesUnchanged = 0; - linesOut = 0; - } - - public: // functions - void convertLineEnds(ostringstream &out, int lineEnd); - FileEncoding detectEncoding(const char* data, size_t dataSize) const; - void error() const; - void error(const char* why, const char* what) const; - void formatCinToCout(); - vector getArgvOptions(int argc, char** argv) const; - bool fileNameVectorIsEmpty() const; - bool getFilesAreIdentical() const; - int getFilesFormatted() const; - bool getIgnoreExcludeErrors() const; - bool getIgnoreExcludeErrorsDisplay() const; - bool getIsDryRun() const; - bool getIsFormattedOnly() const; - bool getIsQuiet() const; - bool getIsRecursive() const; - bool getIsVerbose() const; - bool getLineEndsMixed() const; - bool getNoBackup() const; - bool getPreserveDate() const; - string getLanguageID() const; - string getNumberFormat(int num, size_t = 0) const; - string getNumberFormat(int num, const char* groupingArg, const char* separator) const; - string getOptionsFileName() const; - string getOrigSuffix() const; - void processFiles(); - void processOptions(vector &argvOptions); - void setBypassBrowserOpen(bool state); - void setIgnoreExcludeErrors(bool state); - void setIgnoreExcludeErrorsAndDisplay(bool state); - void setIsDryRun(bool state); - void setIsFormattedOnly(bool state); - void setIsQuiet(bool state); - void setIsRecursive(bool state); - void setIsVerbose(bool state); - void setNoBackup(bool state); - void setOptionsFileName(string name); - 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 updateExcludeVector(string suffixParam); - vector getExcludeVector() const; - vector getExcludeHitsVector() const; - vector getFileNameVector() const; - vector getOptionsVector() const; - vector getFileOptionsVector() const; - vector getFileName() const; - - private: // functions - ASConsole &operator=(ASConsole &); // not to be implemented - void correctMixedLineEnds(ostringstream &out); - 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 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 launchDefaultBrowser(const char* filePathIn = NULL) const; - void printHelp() const; - void printMsg(const char* msg, const string &data) const; - void printSeparatingLine() const; - void printVerboseHeader() const; - void printVerboseStats(clock_t startTime) const; - FileEncoding readFile(const string &fileName_, stringstream &in) 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 writeFile(const string &fileName_, FileEncoding encoding, ostringstream &out) const; +private: // functions + ASConsole& operator=(ASConsole&); // not to be implemented + void correctMixedLineEnds(ostringstream& out); + 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 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 launchDefaultBrowser(const char* filePathIn = NULL) const; + void printHelp() const; + void printMsg(const char* msg, const string& data) const; + void printSeparatingLine() const; + void printVerboseHeader() const; + void printVerboseStats(clock_t startTime) const; + FileEncoding readFile(const string& fileName_, stringstream& in) 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 string& currentEOL); + void sleep(int seconds) const; + int waitForRemove(const char* oldFileName) const; + int wildcmp(const char* wild, const char* data) const; + void writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const; #ifdef _WIN32 - void displayLastError(); + void displayLastError(); #endif }; #else // ASTYLE_LIB @@ -392,19 +382,19 @@ class ASConsole class ASLibrary { - public: - ASLibrary() {} - virtual ~ASLibrary() {} - // virtual functions are mocked in testing - utf16_t* formatUtf16(const utf16_t*, const utf16_t*, fpError, fpAlloc) const; - virtual utf16_t* convertUtf8ToUtf16(const char* utf8In, fpAlloc fpMemoryAlloc) const; - virtual char* convertUtf16ToUtf8(const utf16_t* pSourceIn) const; +public: + ASLibrary() {} + virtual ~ASLibrary() {} + // virtual functions are mocked in testing + utf16_t* formatUtf16(const utf16_t*, const utf16_t*, fpError, fpAlloc) const; + virtual utf16_t* convertUtf8ToUtf16(const char* utf8In, fpAlloc fpMemoryAlloc) const; + virtual char* convertUtf16ToUtf8(const utf16_t* pSourceIn) const; - private: - static char* STDCALL tempMemoryAllocation(unsigned long memoryNeeded); +private: + static char* STDCALL tempMemoryAllocation(unsigned long memoryNeeded); - private: - Utf8_16 utf8_16; // utf8/16 conversion methods +private: + Utf8_16 utf8_16; // utf8/16 conversion methods }; #endif // ASTYLE_LIB