Giter Site home page Giter Site logo

uncrustify / uncrustify Goto Github PK

View Code? Open in Web Editor NEW
2.8K 73.0 565.0 28.11 MB

Code beautifier

Home Page: http://uncrustify.sourceforge.net/

License: GNU General Public License v2.0

Shell 0.42% Python 3.94% Perl 0.06% C++ 62.48% C 18.08% Objective-C 3.50% Smalltalk 0.03% C# 1.83% D 6.26% Java 0.50% OpenEdge ABL 0.09% Vala 0.24% Batchfile 0.09% JavaScript 0.14% CMake 0.71% Awk 0.13% Objective-C++ 1.31% Pawn 0.04% Forth 0.03% HTML 0.12%
beautifier beautify code-style format formatter

uncrustify's Introduction

AppVeyor Coverage Status Conan Center


Uncrustify

A source code beautifier for C, C++, C#, Objective-C, D, Java, Pawn and Vala.

Features

  • Highly configurable - 850 configurable options as of version 0.78.1
  • add/remove spaces
    • sp_before_sparen: Add or remove space before '(' of 'if', 'for', 'switch', 'while', etc.
    • sp_compare: Add or remove space around compare operator '<', '>', '==', etc
  • add/remove newlines
    • nl_if_brace: Add or remove newline between 'if' and '{'
    • nl_brace_while: Add or remove newline between '}' and 'while' of 'do' statement
  • add/remove blanklines
    • eat_blanks_before_close_brace: Whether to remove blank lines before '}'
    • nl_max: The maximum consecutive newlines (3 = 2 blank lines)
  • indent code
    • indent_switch_case: indent_switch_case: Spaces to indent 'case' from 'switch'
    • indent_class_colon: Whether to indent the stuff after a leading base class colon
  • align code
    • align_func_params: Align variable definitions in prototypes and functions
    • align_struct_init_span: The span for aligning struct initializer values (0=don't align)
  • modify code
    • mod_full_brace_for: Add or remove braces on single-line 'for' statement
    • mod_paren_on_return: Add or remove unnecessary paren on 'return' statement

Here is an example configuration file, and here is a before and after C source example. That should give you a pretty good idea of what Uncrustify can do.


Binaries

Pre compiled binaries for Windows can be downloaded from the Releases page or from the Sourceforge website.

Build

Python is an "interpreted high-level programming language for general-purpose programming", for this project it is needed to extend the capabilities of CMake.

CMake is a tool that generates build systems (Makefiles, Visual Studio project files, Xcode project files and others).

To generate a build system for Uncrustify using CMake on UNIX-like systems, create a build folder and run CMake from it, making sure to specify Release mode:

$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release ..

Other systems may require other flags (e.g. cmake -G Xcode .. for Xcode).

Then use the build tools of your build system (in many cases this will simply be make, but on Windows it could be MSBuild or Visual Studio). Or use CMake to invoke it:

$ cmake --build . --config Release

If testing is enabled, CMake generates a test target, which you can build using your build system tools (usually make test). This can also be invoked using CTest:

$ ctest -V -C Debug

There is also an install target, which can be used to install the Uncrustify executable (typically make install).

A note on CMake configurations

Some build systems are single-configuration, which means you specify the build type when running CMake (by setting the CMAKE_BUILD_TYPE variable), and the generated files then build that configuration.

An example of a single-configuration build system are Makefiles. You can build the Release or Debug configurations of Uncrustify (from the build folder) with:

$ cmake -DCMAKE_BUILD_TYPE=Release ..
$ make

or

$ cmake -DCMAKE_BUILD_TYPE=Debug ..
$ make

Other build systems are multi-configuration, which means you specify the build type when building.

An example of a multi-configuration build system are Visual Studios project files. When you open the project in Visual Studio, you can select which configuration to build. You can also do this while building from the command line with cmake --build . --config Debug.

Bugs

Post any bugs to the issue tracker found on the projects GitHub page: https://github.com/uncrustify/uncrustify/issues

Please include the following with your issue:

  • a description of what is not working right
  • input code sufficient to demonstrate the issue
  • expected output code
  • configuration options used to generate the output

More about this is in the ISSUE_TEMPLATE

Known problems

Look at the Wiki

Which repositories have uncrustify?

Look here

Contribute

If you want to add a feature, fix a bug, or implement missing functionality, feel free to do so! Patches are welcome! Here are some areas that need attention:

  • Patches for Objective-C support. We really need someone who knows this language as it has more than plenty open issues. A good starting point would be to integrate changes made in the Unity fork
  • Test Java support and provide feedback (or patches!)
  • Test Embedded SQL to see what works
  • A logo of some sort
  • Anything else that you want to do to make it better?

A note about pull requests

Firstly take a look at the CONTRIBUTING.md

Currently we have two continuous integration systems that test your PRs, TravisCI and Appveyor. Tested are the test cases, the formatting of the code base and the output of the command line options.

Test cases can be found in the tests/ directory. Every file ending with .test is a test set. Inside each line with these components is a single test: testNr[!] testConfigFileName testInputFileName [lang]

The configuration file testConfigFileName has to be located inside tests/config, the input file testInputFileName inside tests/input/<testSetName>/, and expected results file inside the tests/expected/<testSetName>/ directory. Expected results have the following naming convention: testNr-testInputFileName.

Optionally a ! can follow the testNr to enable a custom rerun configuration. Rerun configurations need to be named like this: testConfigFileName(without extension)+.rerun+.extension

Also, optionally a language for the input can be provided with lang.

The codebase has to be formatted by the options set up in forUncrustifySources.cfg. Failing to format the sources correctly will cause TravisCI build failures.

The Command line interface (CLI) output is tested by the test_cli_options.py script. It is located inside of tests/cli/ and operates on the subdirectories of that folder.

If a PR is altering the CLI output, files inside those directories might need to be manually updated. This often happens when options are added, removed, or altered. Keep in mind that the version string line (example: # Uncrustify-0.69.0_f) of outputs from commands like --show-config should be replaced with a blank line.

Debugging

The first method is to use uncrustify itself to get debug informations. Using:

   uncrustify -c myExample.cfg -f myExample.cpp -p myExample.p -L A 2>myExample.A

you get two files for the first informations. The p-file gives you details of the parsing process and indentation.

# Line                Tag              Parent          Columns Br/Lvl/pp     Flag   Nl  Text
#   1>              CLASS[               NONE][  1/  1/  6/  0][0/0/0][  10070000][0-0] class
#   1>               TYPE[              CLASS][  7/  7/ 14/  1][0/0/0][  10000000][0-0]       Capteur
#   1>         BRACE_OPEN[              CLASS][ 15/ 15/ 16/  1][0/0/0][ 100000400][0-0]               {

The A-file gives you many details about the run itself, where the process is running thru, which values have the most important variables.

tokenize(2351): orig line is 1, orig col is 1, Text() 'class', type is CLASS, orig col_end is 6
tokenize(2351): orig line is 1, orig col is 7, Text() 'Capteur', type is WORD, orig col_end is 14
tokenize(2351): orig line is 1, orig col is 15, Text() '{', type is BRACE_OPEN, orig col_end is 16

You can also dump the parsing information of each formatting step using the 'dump steps' option.

   uncrustify -c myExample.cfg -f myExample.cpp -ds dump

This will create a series of 'dump_nnn.log' files, each containing the parsing information at specific points of the formatting process ('dump_000.log' will list the formatting options in use).

You can combine this option with -p and -L to get a lot of detailed debugging information.

   uncrustify -c myExample.cfg -f myExample.cpp -p myExample.p -L A 2>myExample.A -ds dump

It might be useful to add some code lines to see where something is happening. Use the package unc_tools. Remove the comment at line:

#define DEVELOP_ONLY

Import the package:

#include "unc_tools.h"

Add at some places the line:

prot_the_line(__LINE__, 6, 0);

Compile again with DEBUG option.

How to add an option

If you need a new option, there are a few steps to follow. Take as example the option sp_trailing_ret_t

First define the option:

  • Insert the code below to the file src/options.h _NOTE: This file is processed by make_options.py, and must conform to a particular format. Option groups are marked by '//begin ' (in upper case; this example is lower case to prevent being considered a region marker for code folding) followed by the group description. Options consist of two lines of declaration preceded by one or more lines of C++ comments. The comments form the option description and are taken verbatim, aside from stripping the leading '// '. Only comments immediately preceding an option declaration, with no blank lines, are taken as part of the description, so a blank line may be used to separate notations from a description. An option declaration is 'extern TYPE\nNAME;', optionally followed by ' // = VALUE' if the option has a default value that is different from the default-constructed value type of the option. The 'VALUE' must be valid C++ code, and is taken verbatim as an argument when creating the option's instantiation. Note also that the line break, as shown, is required. _
// Add or remove space around trailing return operator '->'.
extern Option<iarf_e>
sp_trailing_ret_t;
  • Insert the code below to the file src/space.cpp
   if (first->Is(CT_TRAILING_RET_T))
   {
      // Add or remove space around trailing return operator '->'.
      log_rule("sp_trailing_ret_t");
      return(options::sp_trailing_ret_t());
   }

Portability

We are pretty sure that nothing OS-specific is used in the code base. The software has been previously tested on the following operating systems:

  • Linux
  • QNX
  • OS X
  • FreeBSD, NetBSD, OpenBSD
  • Sun Solaris 9
  • Windows (binary available)

Running the program

NOTE This application works reasonably well but it has bugs. Do not apply it on your whole codebase without checking the results!

Here are ways to run it:

$ uncrustify -c mystyle.cfg -f somefile.c -o somefile.c.unc
$ uncrustify -c mystyle.cfg -f somefile.c > somefile.c.unc
$ uncrustify -c mystyle.cfg somefile.c
$ uncrustify -c mystyle.cfg --no-backup somefile.c
$ uncrustify -c mystyle.cfg *.c
$ uncrustify -c mystyle.cfg --no-backup *.c

The -c flag selects the configuration file. The -f flag specifies the input file. The -o flag specifies the output file. If flag -f is used without flag -o the output will be send to stdout.

Alternatively, multiple or single files that should be processed can be specified at the command end without flags. If the flag --no-backup is missing, every file is saved with the initial name and an additional suffix (can be changed with --suffix).

For more options descriptions call:

$ uncrustify -h

Configuring the program

Uncrustify usually reads configuration files that are passed via the -c flag. If the flag is not provided, Uncrustify will try to find a configuration file via the UNCRUSTIFY_CONFIG environment variable or a file with the name .uncrustify.cfg or uncrustify.cfg in your home folder.

To get a list of:

  • all available options use:

    uncrustify --show-config
  • all available options in a usable configuration file format use:

    uncrustify --update-config

    or

    uncrustify --update-config-with-doc

    As the names suggest, both options can produce output that adds newly introduced options to your old configuration file. For this your old configuration file has to be passed via the -c flag:

    uncrustify --update-config-with-doc -c path/to/your.cfg

Example configuration files that can be used as a starting point can be found in the etc/ directory (such as ben.cfg).

Modify to your liking. Use a quality side-by-side diff tool to determine if the program did what you wanted. Repeat until your style is refined.

To ease the process a bit, some 3rd party tools are available:

  • Universal Indent GUI - A cross-platform graphical configuration file editor for many code beautifiers, including Uncrustify.
  • uncrustify_config - A web configuration tool based on Uncrustify's emscripten interface.
  • UncrustifyX - Uncrustify utility and documentation browser for Mac OS X

Under Windows: Uncrustify is a command-line tool, if you run it by double-clicking the executable, it will open a command prompt run the executable (which prints the help message), and then immediately close the window as uncrustify exits.

You can open the command prompt (which is an interactive terminal window that allows you to run commands without it closing as soon as they exit) and run uncrustify.exe there.

Using uncrustify with vim

Have a look here

Using uncrustify with IntelliJ

Have a look at https://plugins.jetbrains.com/plugin/17528-uncrustify

uncrustify's People

Contributors

alexhenrie avatar andreberg avatar andrey-starodubtsev avatar bengardner avatar cdanu avatar charlieyjh avatar dbartolini avatar dirk-thomas avatar dundargoc avatar fwojcik avatar geimer avatar gmaurel avatar guy-maurel avatar ib avatar javdevgames avatar jibsen avatar krizai avatar kvic avatar michelectde avatar michelectdeadmin avatar mihai-unity avatar mwoehlke avatar mwoehlke-kitware avatar nivekkagicom avatar parkerjs avatar rdan avatar samishchandra avatar scottbilas avatar sjakub avatar stefan-nu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uncrustify's Issues

Whitespace Stripping

It would be nice if uncrustify had an option for whitespace stripping:

  • from the end of each line;
  • of blank lines from the end of a file, ensuring the file ends with one newline.

(Apologies if this is already there, but I couldn't find an option for it.)

Constructor definition : member initialization

I am not sure if this is an issue or, perhaps, there is already an option to control it... Given this constructor:

Thread::Thread()
    :   m_bStarted(false),
    m_log("/Thread")
{
    m_pOsSpecific = new OsPimpl;
}

It would be nice to have the second and other members indented, so that they form a vertical column. indent_ctor_init does not help here. Tested on bengardner-uncrustify-82f70d3.

Struct unrecognized in C++

Uncrustify generates a warning whenever 'struct' is used as a synonym for class in my C++ project. Specifically, it complains about unexpected chunk's BRACE_OPEN and COLON like so:

???: 34:49 unexpected chunk BRACE_OPEN '{' - please report
???: 45:28 unexpected chunk COLON ':' - please report

using version 0.58

Objective C header miss-aligned parameters

Header file:

@interface X : NSObject {
}
- (X *) create:(UITableViewController *) controller
             a:(NSObject *) delegate
             b:(NSInteger) tag
             c:(NSString *) hint
             d:(NSString *) text;

@end

After formatting:

@interface X : NSObject {
}
- (X *) create:(UITableViewController *) controller
  a           :(NSObject *) delegate
  b           :(NSInteger) tag
  c           :(NSString *) hint
  d           :(NSString *) text;
@end

The problem is that I cannot figure out how to get the variable names to stay against the colons. Following is the config used

#
# uncrustify config file for objective-c and objective-c++
#

indent_with_tabs        = 2     # 1=indent to level only, 2=indent with tabs
output_tab_size         = 3     # new tab size
indent_columns          = output_tab_size
indent_label            = 2     # pos: absolute col, neg: relative column
indent_align_assign     = TRUE

# Macros.
pp_indent = remove

#
# Indenting
#

# indent_brace          = 0
indent_switch_case      = indent_columns

#
# Inter-symbol newlines
#

nl_enum_brace         = remove   # "enum {" vs "enum \n {"
nl_union_brace        = remove   # "union {" vs "union \n {"
nl_struct_brace       = remove   # "struct {" vs "struct \n {"
nl_do_brace           = remove   # "do {" vs "do \n {"
nl_if_brace           = remove   # "if () {" vs "if () \n {"
nl_for_brace          = remove   # "for () {" vs "for () \n {"
nl_else_brace         = remove   # "else {" vs "else \n {"
nl_while_brace        = remove   # "while () {" vs "while () \n {"
nl_switch_brace       = remove   # "switch () {" vs "switch () \n {"
nl_brace_while        = remove   # "} while" vs "} \n while" - cuddle while
nl_brace_else         = remove   # "} else" vs "} \n else" - cuddle else
nl_func_var_def_blk   = 1
nl_fcall_brace        = remove   # "list_for_each() {" vs "list_for_each()\n{"
nl_fdef_brace         = remove   # "int foo() {" vs "int foo()\n{"
# nl_after_return     = TRUE;
# nl_before_case      = 1


#
# Source code modifications
#

mod_paren_on_return                       = ignore # "return 1;" vs "return (1);"
mod_full_brace_if                         = ignore    # "if (a) a--;" vs "if (a) { a--; }"
mod_full_brace_for                        = add       # "for () a--;" vs "for () { a--; }"
mod_full_brace_do                         = ignore # "do a--; while ();" vs "do { a--; } while ();"
mod_full_brace_while                      = remove # "while (a) a--;" vs "while (a) { a--; }"
mod_full_brace_nl                         = 3          # don't remove if more than 3 newlines
mod_add_long_ifdef_endif_comment          = 20
mod_add_long_ifdef_else_comment           = mod_add_long_ifdef_else_comment
mod_add_long_switch_closebrace_comment    = mod_add_long_ifdef_else_comment
mod_add_long_function_closebrace_comment  = mod_add_long_ifdef_else_comment

#
# Inter-character spacing options
#

# sp_return_paren         = force      # "return (1);" vs "return(1);"
sp_sizeof_paren              = remove  # "sizeof (int)" vs "sizeof(int)"
sp_before_sparen             = force      # "if (" vs "if("
sp_after_sparen              = force      # "if () {" vs "if (){"
sp_after_cast                = remove  # "(int) a" vs "(int)a"
sp_inside_braces             = add     # "{ 1 }" vs "{1}"
sp_inside_braces_struct      = add     # "{ 1 }" vs "{1}"
sp_inside_braces_enum        = add     # "{ 1 }" vs "{1}"
sp_inside_fparen             = remove    # "func( param )" vs "func(param)"
sp_inside_square             = remove  # [ abc ] => [abc]
sp_paren_brace               = force
sp_after_cast                = force   # (abc)x => (abc) x
sp_assign                    = add
sp_arith                     = add
sp_bool                      = add
sp_compare                   = add
sp_assign                    = add
sp_after_comma               = add
sp_func_def_paren            = remove  # "int foo (){" vs "int foo(){"
sp_func_call_paren           = remove  # "foo (" vs "foo("
sp_func_proto_paren          = remove  # "int foo ();" vs "int foo();"
sp_before_ptr_star           = force 
sp_after_ptr_star            = force
sp_before_unnamed_ptr_star   = ignore
sp_between_ptr_star          = remove
sp_after_ptr_star_func       = force
sp_before_ptr_star_func      = force
sp_cmt_cpp_start             = force
sp_cond_question             = force
sp_cond_colon                = force
sp_else_brace                = force
sp_brace_else                = force
sp_after_class_colon         = force
sp_before_class_colon        = force
sp_before_case_colon         = remove

# Objective-C specifics      
sp_before_oc_colon           = remove
sp_after_oc_colon            = remove
sp_after_oc_scope            = force
sp_after_oc_type             = force
sp_after_oc_return_type      = force
sp_before_send_oc_colon      = remove
sp_after_send_oc_colon       = remove
sp_after_oc_at_sel           = remove
sp_before_oc_block_caret     = ignore
sp_after_oc_block_caret      = remove
sp_after_semi                = remove

#
# Aligning stuff
#

align_with_tabs               = False     # use tabs to align
align_on_tabstop              = False     # align on tabstops
# align_keep_tabs             = True
align_enum_equ_span           = 4         # '=' in enum definition
# align_nl_cont               = True
# align_var_def_span          = 2
# align_var_def_inline        = True
# align_var_def_star          = False
# align_var_def_colon         = True
# align_assign_span           = 1
align_struct_init_span        = 4         # align stuff in a structure init '= { }'
align_right_cmt_span          = 8
align_right_cmt_gap           = 8
align_pp_define_span          = 8
#align_pp_define_gap          = 8
align_oc_msg_colon_span       = 99         # align parameters in an Obj-C message on the ':' but stop after this many lines (0=don't align)
align_oc_msg_spec_span        = 1         # the span for aligning ObjC msg spec (0=don't align)
align_oc_decl_colon           = True

#
# Line Splitting options
#

# ls_func_split_full          = True     # Whether to fully split long function protos/calls at commas

#
# Comment modifications
#

cmt_star_cont                 = True     # Whether to put a star on subsequent comment lines
indent_relative_single_line_comments = true

ObjC - Misunderstand as keyword which is method name (do, while, for ...)

Method names with do, while, for ... (C keywords) are misunderstood as keyword.
If i write the method as

@interface Sample: Object

  • do;
  • doWith: ... for:... ;
    @EnD

and use like
[instance do];
[instance doWith: ... for: ...];

there are errors which is incorrect.

Here it is.

Action.m:1208 Error: Expected '(', got ':' for 'FOR'
Action.m:1208 Error: Expected '(', got ':' for 'FOR'
Action.m:1211 Error: Expected '(', got ':' for 'FOR'
Action.m:1211 Error: Expected '(', got ':' for 'FOR'
Action.m:1229 Error: Expected 'while', got '-'
Action.m:1307 Error: Unexpected ']' for 'VBRACE_OPEN', which was on line 1306
Action.m:1308 Error: Expected 'while', got '}'
Action.m:1308 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1305
Action.m:1329 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1305
Action.m:1450 Error: Expected '(', got ':' for 'FOR'
Action.m:1462 Error: Expected '(', got ':' for 'FOR'
Action.m:1469 Error: Expected '(', got ':' for 'FOR'
Action.m:1474 Error: Expected '(', got ':' for 'FOR'
Action.m:1476 Error: Expected '(', got ':' for 'FOR'
Action.m:1485 Error: Expected '(', got ':' for 'FOR'
Action.m:1802 Error: Unexpected ']' for 'VBRACE_OPEN', which was on line 1801
Action.m:1803 Error: Expected 'while', got '}'
Action.m:1803 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1800
Action.m:1804 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1800
Action.m:1805 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1800
Action.m:1829 Error: Unexpected '}' for 'SQUARE_OPEN', which was on line 1800
Action.m:1282 Unmatched BRACE_OPEN
Action.m:1304 Unmatched BRACE_OPEN
Action.m:1305 Unmatched ASSIGN
Action.m:1305 Unmatched SQUARE_OPEN
Action.m:1594 Unmatched BRACE_OPEN
Action.m:1607 Unmatched BRACE_OPEN
Action.m:1615 Unmatched BRACE_OPEN
Action.m:1799 Unmatched BRACE_OPEN
Action.m:1800 Unmatched ASSIGN
Action.m:1800 Unmatched SQUARE_OPEN
Action.m:1282 Unmatched BRACE_OPEN
Action.m:1304 Unmatched BRACE_OPEN
Action.m:1305 Unmatched ASSIGN
Action.m:1305 Unmatched SQUARE_OPEN
Action.m:1594 Unmatched BRACE_OPEN
Action.m:1607 Unmatched BRACE_OPEN
Action.m:1615 Unmatched BRACE_OPEN
Action.m:1799 Unmatched BRACE_OPEN
Action.m:1800 Unmatched ASSIGN
Action.m:1800 Unmatched SQUARE_OPEN

ObjC - spurious spaces in macro with method name

I use a macro to register for NSNotifications, and spaces get inserted before and/or after the colon in the method name.
LocalObserver(@"notificationName", myMethod:);
becomes
LocalObserver(@"notificationName", myMethod : );
with spaces surrounding the colon - before, after or both.

BTW, the macro is defined as:
#define LocalObserver(n, s) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(s) name:n object:nil]

Again, I'm not sure if it's a misconfiguration or bug. Thanks.

Wrong description of param ?

Add or remove newline between ')' and 'throw'

nl_before_throw = remove # ignore/add/remove/force

I've noticed that this param has effect on following code
if (x)
{
throw std::exception("hi");
}
removing newline before throw, but description has ')' in text.

I guess this param should change this layout:
if (x) throw new std::exception("HI");

but it doesn't change anything. My settings for one liners are to keep them one line.

Casts in C++

I've just noticed that some casts receive additional unexpected spacing:

    uint32 idx = something + (uint32) std::distance(blocks.begin(), b);
    uint32 idx2 = (uint32)something;

Note the extra space just on the first line.

Objective-C: Pointer stars not correctly interpreted for blocks

request.callback = ^(uint status, NSData *data) {
};

is turned into

request.callback = ^(uint status, NSData * data) {
};

with the following settings:

# Add or remove space around arithmetic operator '+', '-', '/', '*', etc
sp_arith                                 = force   # ignore/add/remove/force
# Add or remove space between pointer stars '*'
sp_between_ptr_star                      = remove   # ignore/add/remove/force

The pointer star is apparently interpreted as an arithmetic operator in this case.

Objective-C: sp_func_call_paren not working after using a block

The following code is being formatted correctly:

[something somewhat];
func(nil);

However, adding a block somewhere causes an extra space after func:

[something somewhat:^{}];
func (nil);

Expected behavior: no space after func as above.

This happens with the default configuration as well as with the following:

# Add or remove space between function name and '(' on function calls
sp_func_call_paren                       = remove   # ignore/add/remove/force

sp_func_call_paren=remove not working?

I have a lot of cases where uncrustify is adding spaces before parens in function calls, even though I have sp_func_call_paren set to remove. It's also not consistent - some instances of NSLog, for example, are treated correctly and others not.

I'm seeing this in the Uncommon/Xit project, where we're running uncrustify in a build script.

Segmentation Fault with nl_define_macro=true, nl_if_brace=force and partial macros

Hi,

uncrustify is core dumping when I use it on some C code with a macro not ended with a semicolon such a this one:

#define PRINT(foo, bar) if(foo) printf("bar")

and this simple uncrustify configuration:

nl_define_macro=true
nl_if_brace=force

A simple C file containing the statement above and running uncrustify with the config file below is enough to make it core dump.

Objective-C blocks: Allow aligning just like regular blocks

Currently, uncrustify indents Objective-C blocks like this:

id foo = [bar execute:^(NSNumber * value) {
              [value doSomething];
          }];

The following seems to be the most common way to indent this and I'd like to request an option for it:

id foo = [bar execute:^(NSNumber * value) {
    [value doSomething];
}];

The mixed indentation seems to be off, too. [value doSomething] is indented mostly using spaces, }] using mostly tabs.

input_tab_size                          = 4        # number
output_tab_size                         = 4        # number

C++11 lambda functions

It would be cool to support C++11 lambdas so that argument declarations are treated correctly:

auto f = base::MakeFuture(
    this,
    [ = ](Client * cli, base::Thread &, base::Promise & p)
    {
        cli->SaveConnectionPromise(p);
    });

Tested with bengardner-uncrustify-82f70d3:

  • the "Client * cli" part should have had the space stripped off
  • I am guessing these are treated as binary operators?
  • normal function declarations are processed correctly and produce "Client *cli"
  • the same goes for the reference
  • also, extra spaces are added around the = sign as, I am guessing, it is treated as assignment

Thanks!

Xcode project doesn't build

The Xcode project fails to build with link errors because unc_text.cpp and unicode.cpp are missing from the target.

Bad file generated for UniversalIndentGUI

It misses labels (ChoicesReadable) associated with choice values lead_break, lead_force... in file generated with the following command line:
Uncrustify.exe --universalindent -o uigui_uncrustify.ini

nl_after_XX and nl_before_XX not respected for if/comment chains

The expected behavior is that there should be a newline between the closing brace } and the following comment.

Configuration

nl_after_if = add
nl_after_brace_close = true
nl_before_cpp_comment = 1
nl_before_c_comment = 1

Input

//
// Comments
//
if(x)
{
    // ...
}
//
// Comments
//
else ( ... )
{
    // ...
}
//
// More comments
//

Expected Output

//
// Comments
//
if(x)
{
    // ...
}

//
// Comments
//
else ( ... )
{
    // ...
}

//
// More comments
//

Feature request: parameter to reformat function calls

There is parameter 'nl_func_decl_args' to
'Add or remove newline after each ',' in a function declaration'

but there is nothing like that for function calls
The most close one is 'pos_comma', but it can't remove new lines, but just add/force them. Not sure about the difference between 'trail_break' and 'trail_force' by the way, but it does what it should.

It would be great to remove new lines in function calls applying 'trail'/'lead' and adding new lines according to desired code width param.

May be i missed smth?

Thanks

Spaces and blank lines while formatting java code

Uncrustify adds a space between class and ')' in the below code. Dont know why.

private static Logger logger = Logger.getLogger(ExcelCellReader.class );

If there are blank lines between class and ')', and between ')' and ';', uncrustify does not remove them.

private static Logger logger = Logger.getLogger(ExcelCellReader.class )
;

In the above code, the ';' should align with the ')', it does not.

private static Logger logger = Logger.getLogger(ExcelCellReader.class

    );

Uncrustify does not remove the blank line, in the above code.

Does not align on SBOOL types

|| and or are not treated equally for the purposes of aligning wrapped conditionals.

if (  A
   || B )

vs

if ( A
     or B)

cmt_insert_oc_msg_header missing $(javaparam) output

Not sure if I'm messed up, but I can't get the parameters generated in comment block.

Content in the comment header file:
/**

  • $(message)
  • *
  • $(javaparam)
    */

Generated comment:
/**

  • setObject:forKey:
  • * * */ - (void)setObject:(id)value forKey:(id)key

Whitespace removed around ":" in ternary operator within Objective C method

uncrustify turns this:

[string appendFormat:@"%s", (foo) ? "foo" : "bar"];

into this:

[string appendFormat:@"%s", (foo) ? "foo":"bar"];

which sucks.

Not sure though, if this happens exclusively when used within methods, or also in other situations.

It will properly preserve the whitespace in this line though:

char *fooBar = (foo) ? "foo" : "bar";

Templated function calls

It would be cool to support templated function calls that have >>:

auto servers = r.Get<std::vector<uint32 >> ("placement");

Tested with bengardner-uncrustify-82f70d3:

  • tok_split_gte = false
    sp_angle_shift = remove
  • the >> part got extra spaces

blank lines and spaces between words and closing parenthesis

  • If there is a space/newline between a word and closing parenthesis, uncrustify does not remove it. For e.g.

    private static Logger logger = Logger.getLogger(ExcelCellReader.class );

Note the space between 'class' and ')'

  • Also, if there are more than one blank lines between class and ')', uncrustify does not remove them completely. It leaves at least one blank line.

    private static Logger logger = Logger.getLogger(ExcelCellReader.class
    // 2 blank lines.

    );

This becomes

private static Logger logger = Logger.getLogger(ExcelCellReader.class

);

Ternary operator issue

The following exception is thrown when "assert ( a != null ) && ( b != null ) : Messages.getString( "awt.74" );" is parsed:

JavaBug2.java:5 unexpected colon in col 47 n-parent=NONE c-parent=NONE l=2 bl=2

The following exception is thrown when "
while( skipped < length && ( count = read( buffer, 0, ( length - skipped > buffer.length ) ? buffer.length : length - skipped ) ) >= 0 ) {
skipped += count;
}
" is parsed:

JavaBug.java:5 Error: Unexpected '>' for 'PAREN_OPEN', which was on line 5
JavaBug.java:5 Error: Unexpected ')' for 'ANGLE_OPEN', which was on line 5
JavaBug.java:11 Error: Unexpected '}' for 'ANGLE_OPEN', which was on line 5
JavaBug.java:12 Error: Unexpected '}' for 'ANGLE_OPEN', which was on line 5
JavaBug.java:1 Unmatched BRACE_OPEN
JavaBug.java:3 Unmatched BRACE_OPEN
JavaBug.java:5 Unmatched SPAREN_OPEN
JavaBug.java:5 Unmatched ANGLE_OPEN
JavaBug.java:1 Unmatched BRACE_OPEN
JavaBug.java:3 Unmatched BRACE_OPEN
JavaBug.java:5 Unmatched SPAREN_OPEN
JavaBug.java:5 Unmatched ANGLE_OPEN

They are likely both related to the ternary operator.

Cannot install

This very well could be only me, since I cannot find anyone else having this issue. I simply cannot install. tried macports as well.

The following build commands failed:

    CompileC build/uncrustify.build/Install/uncrustify.build/Objects-normal/x86_64/options.o src/options.cpp normal x86_64 c++ com.apple.compilers.llvmgcc42
    CompileC build/uncrustify.build/Install/uncrustify.build/Objects-normal/x86_64/uncrustify.o src/uncrustify.cpp normal x86_64 c++ com.apple.compilers.llvmgcc42
    CompileC build/uncrustify.build/Install/uncrustify.build/Objects-normal/x86_64/universalindentgui.o src/universalindentgui.cpp normal x86_64 c++ com.apple.compilers.llvmgcc42
(3 failures)

PRIu64 is modified to "PRIu 64"

In v0.58, the following change was applied:
-INF("current_size=%"PRIu64" expected_size=%"PRIu64, current_size, expected_size);
+INF("current_size=%"PRIu 64 " expected_size=%"PRIu 64, current_size, expected_size);

This is in patch to WebKit:

https://bugs.webkit.org/attachment.cgi?id=107766

Using v0.56 this doesn't occur. I tried manually setting some token type in my config, but none of them removed this error.

Possible problem with obj-c method declarations and alignment

I'm experiencing problems with the alignment of the following method:


- (void)test:(NSString *)param1
      param2:(NSString *)param2
      param3:(NSString *)param3
      param4:(NSString *)param4;

When uncrustify is run, it delivers the following:


- (void)test:(NSString *)param1
   param2   :(NSString *)param2
   param3   :(NSString *)param3
   param4   :(NSString *)param4;

I have used "align_oc_decl_colon = True" in the configuration file.

language OC @protocol(MyClass)

e.g. OCMock requires idioms like

id mock = [OCMockObject mockForProtocol:@protocol(MyClass)];

which makes v0.53 choke.

Workaround:

#define UNCRUSTIFY_SAFE_PROTOCOL(x)     @protocol(x)
...
id mock = [OCMockObject mockForProtocol:UNCRUSTIFY_SAFE_PROTOCOL(MyClass)];

Ability to provide additional qualifier identifiers

Is there any way to get an output where alignments can work like so with IN and OUT keywords (#define'd to whitespace). They have no meaning in source, they are just for API documentation.'

I've tried defining "IN OUT", "IN____" and "___OUT" as identifiers, but this doesn't have the desired effect. (replace '_' with a space).

    /**
     * Blah Documentation Blah
     */
    int
    SomeFunction (
        IN OUT int  *blah,
        IN     int   blah2,
           OUT void *blah3
    )

ObjC - space before withObject: removed

I'm not sure if this is a bug or a misconfiguration, but I've been unable to find a config option to suppress removal of the space before the withObject: after @selector( ) in these types of statements:
[myObj performSelectorOnMainThread:@selector(mySel) withObject:nil waitUntilDone:NO];
becomes:
[myObj performSelectorOnMainThread:@selector(mySel)withObject:nil waitUntilDone:NO];

Thanks for a great utility, BTW.

Objective-C blocks gaining spurious spaces

I'm not sure if this is the same issue as #22 (it looks similar), but I'm seeing some odd behaviour around formatting Objective-C blocks:

typedef void (^ CancelBlock)();
typedef void (^ PhotoPickedBlock)(NSDictionary *chosenItemDetails);

Should be:

typedef void (^CancelBlock)();
typedef void (^PhotoPickedBlock)(NSDictionary *chosenItemDetails);

And then when it is used in the header (.h):

+ (void)imagePickerWithTitle:(NSString *)title showInView:(UIView *)view presentVC:(UIViewController *)presentView onPhotoPicked:(PhotoPickedBlock) photoPicked onCancel:(CancelBlock)cancelled;

Should be:

+ (void)imagePickerWithTitle:(NSString *)title showInView:(UIView *)view presentVC:(UIViewController *)presentView onPhotoPicked:(PhotoPickedBlock)photoPicked onCancel:(CancelBlock)cancelled;

Oddly, it only seems to affect the first declaration, and the implementation (.m) file is unaffected by this problem.

Uncrustify spacing issue with macro inside method call

I am attempting to use Uncrustify on a project of mine, but I am running into some issues with spacing changes that it makes when a macro is used as the receiver of an Objective-C message. For example, given the following macro and method call, I would expect the spacing to remain exactly as is.

#define NilOrNotNSNull(val) ({id __val = (val); (__val == [NSNull null]) ? nil : __val;})

title_ = [NilOrNotNSNull([dict objectForKey:@"post_title"]) copy];

However, this is the result.

#define NilOrNotNSNull(val) ({id __val = (val); (__val == [NSNull null]) ? nil : __val;})

title_ = [NilOrNotNSNull ([dict objectForKey:@"post_title"])copy];

It appears as if Uncrustify does not recognize that the text in parentheses is an argument for the macro, but then I'm not really sure what the heck it thinks it is. This seems like an Uncrustify bug to me, but it could be an issue with my config. Here is the config I'm using: https://gist.github.com/812314

Protocol casts get messed up in Objective C code (whitespace)

This:

- (void)aMethod {
    return [(id<MyProtocol>)myVar myMethod:myArgument];
}

turns into:

- (void)aMethod {
    return [(id < MyProtocol >) myVar myMethod:myArgument];
}

which sucks.

And so I'm forced to do this:

- (void)aMethod {
    return [((id<MyProtocol>)myVar) myMethod:myArgument];
}

which will turn into this:

- (void)aMethod {
    return [((id < MyProtocol >)myVar) myMethod:myArgument];
}

which sucks a little less, but still sucks way too much. ;)

But apart from this and my previous small tickets uncrustify is incredibly awesome! Keep up the great work!

nl_func_type_name and nl_func_type_name_class treat access specifier as constructor return

config:
indent_columns = 2
indent_with_tabs = 0
indent_class = true
indent_access_spec = 1
nl_func_type_name = remove
nl_func_type_name_class = remove
nl_func_proto_type_name = remove

input:
class Foo
{
public:
Foo(void);

  void
    bar(void);
};

output:

class Foo
{
public: Foo(void);

  void bar(void);
};

This is true whether nl_func_type_name or nl_func_type_name_class are used together or independently.

mod_full_brace_if doesn't use "force" properly

Per htdocs/configuration.txt, force == add when not dealing with a spaces context. At least with mod_full_brace_if, this does not appear to work.

Sample C++ code:
int main(int argc, char* argv[])
{
if (argc)
return argc;
return 0;
}

Sample config:
mod_full_brace_if = force

Diff between original and obtained:
int main(int argc, char* argv[])
{
- if (argc)
- return argc;
- return 0;
+ if (argc)
+ return argc;return 0;
}

Changing "force" to "add" results in the following diff:

 int main(int argc, char* argv[])
 {
-  if (argc)
-    return argc;
-  return 0;
+   if (argc) {
+       return argc;
+   }
+   return 0;
 }

I can switch to "add" in my configuration, but something's broken (either the docs or the code).

Macros and stream operators

I use a macro together with the stream operator (<<) to write into the log. bengardner-uncrustify-82f70d3 produces the following code:

LOG(hanle_) 
<< "Some output: " << arg << " more output";

It would be really cool to be able to state that these "follow on" lines are indented. Thanks!

nl_func_type_name removes lines between public: label and destructor

If I have the following class

class Test
{
public:
  ~Test();
};

and my config file is the default with one change

nl_func_type_name                        = remove   # ignore/add/remove/force

the code ends up formatted as

class Test
{
public: ~Test();
};

it seems that uncrustify is confusing the access label for a return value.

mod_move_case_break and mod_case_brace don't work well together.

config:
mod_move_case_break = true
mod_case_brace = add

input:
void f(int v)
{
switch (v) {
case 0:
case 1:
break;
default:
break;
}
}

output:

void f(int v)
{
    switch (v) {
    case 0:
    case 1: {
    } break;
    default: {
    } break;
    }
}

The break; should be inside of the braces added by mod_case_break.

Block code in Objective-C

Hi all,

With my configuration file (see the link bellow), I get the following result where there should be tree lines between foo and bar. But there's not… it seems the reason is the code block with a parameter. There is an other case where I get the same bug: when there is not parameter to the block and the block is empty (i.e. replacing the block by: [UIView buzz:^ {}];).

By the way I'm missing an option to put the code block opening brace on a new line, is there something like that? Or would it be hard to add this myself, without knowing the inner of Uncrustify?

Config file : http://dl.dropbox.com/u/2820534/temporaire/uncristify_objc_code_block_test.cfg

Thanks in advance,
Mathieu

@implementation Bleep

- (void)fizz
{
    return;
}



- (void)foo
{
    [UIView buzz:^ (BOOL finished) {
     }
    ];
}

- (void)bar
{
    return;
}



@end

Uncrustify as a library

Any chance that uncrustify will be available as a library for use in other programs? I'm thinking text editors and such.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.