1. Commonly Used Functions
(1) Beautify a Single File
To beautify a single file with default settings:
astyle --style=ansi Form1.cs
Before formatting:
private void Form1_Load(object sender, EventArgs e)
{
int s;
for (int i=0;i<10;i++){
for (int j=0;j<10; j++){
s = s+j+i;}
}
}
After formatting:
private void Form1_Load(object sender, EventArgs e)
{
int s;
for (int i=0;i<10;i++)
{
for (int j=0;j<10; j++)
{
s = s+j+i;
}
}
}
(2) Change Indentation to 3 Spaces
To change the indentation to 3 spaces:
astyle --style=ansi --indent=spaces=3 Form1.c
Alternatively, using tabs explicitly:
astyle --style=ansi --indent=tab Form1.cs
(3) Process Multiple Files (Limited Number)
To process multiple files (a finite number):
astyle --style=ansi Form1.cs Form2.cs
(4) Batch Process Multiple Files (Unlimited Number)
To batch process an unlimited number of files:
for /R .\ %f in (*.cs) do astyle --style=ansi "%f"
Explanation: /R
traverses the directory tree starting from the current directory (.\
). It searches for all .cs
files and applies astyle
to each of them.
2. Other Useful Switches (precede --style
)
(1) -f
Inserts blank lines between unrelated lines of code, such as between imports and public class
, or between public class
and members.
(2) -p
Inserts spaces around operators like =
, +
, -
, etc.
Example: int a=10*60;
becomes int a = 10 * 60;
.
(3) -P
Inserts spaces around parentheses. -d
inserts spaces only outside parentheses, and -D
inserts spaces only inside.
Example: MessageBox.Show ("aaa");
becomes MessageBox.Show ( "aaa" );
.
(4) -U
Removes unnecessary spaces around parentheses.
Example: MessageBox.Show ( "aaa" );
becomes MessageBox.Show ("aaa");
.
(5) -V
Replaces tabs with spaces.
Integration with SourceInsight on Windows
Many developers on Windows use SourceInsight for editing C/C++ programs, which lacks built-in code formatting functionality. Integrating Artistic Style (astyle
) with SourceInsight can extend its capabilities:
- Open SourceInsight and go to
Options
->Custom Commands
->Add
. - Enter a name (e.g., Artistic Style) and set
Run
toC:\ArtisticStyle\Astyle.exe --options=c.opt %f
. - Leave
Dir
empty and checkIconic Window
,Capture Output
,Parse Links in Output
,File
, andLine
. - Click
Menu
in theOptions
dialog, thenMenu
->Menu
->View
-><end of menu>
->Insert
, andOK
. - Now, under the
View
menu in SourceInsight, you’ll find aStyle
submenu option to format individual C/C++ files.
This guide enhances the usability of astyle
for code formatting and demonstrates integration with SourceInsight for enhanced development workflows.