Tag Archives: pretty printer

Pretty printing C++ with Clang-Format

I use some of the code generation and refactoring tools in QtCreator. These save a lot of time, but they don’t format C++ code how I like it. For example they produce C++ code like this:

void MyClass::foo(int *x)

But I like my code formatted like this:

void MyClass::foo( int* x )

The differences may seem minor, but they are a source of significant irritation to me. I like my code how I like it, goddammit! And consistent formatting enhances readability. However re-formatting it by hand is time-consuming and tedious.

What I need is a tool that can enforce consistent formatting in the style that I like, or something close. I have tried to use automatic C++ formatting (pretty printing) tools in the past, but I couldn’t get them to produce a format that was close enough to what I wanted. But I have finally found the tool for the job. Clang-Format.

Clang-Format is part of the LLVM family of tools. It is a free, command-line tool that reformats C++, Objective-C or C according to the settings in a config file. As with many free tools, it isn’t terribly well documented. Some of the documentation on the web is out of date and some of it is incomplete. But I have managed to find out enough to configure it how I like it.

To run it you just need to place your options in a .clang-format file, make sure the clang-format executable is in the path and then run it:

clang-format.exe -i -style=file <C++ file>

Here are the settings I am currently using in my .clang-format file:

Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: false
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
  AfterClass:      true
  AfterControlStatement: true
  AfterEnum:       true
  AfterFunction:   true
  AfterNamespace:  true
  AfterObjCDeclaration: true
  AfterStruct:     true
  AfterUnion:      false
  BeforeCatch:     true
  BeforeElse:      true
  IndentBraces:    false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 0
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 0
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
PenaltyBreakBeforeFirstCallParameter: 100
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 10000
PointerAlignment: Left
ReflowComments: true
SortIncludes: false
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: true
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: true
SpacesInParentheses: true
SpacesInSquareBrackets: true
Standard: Cpp11
TabWidth: 4
UseTab: Never

It took me a few hours of fiddling with the settings to find the best combination. It would be really useful if someone could write a tool that would analyze your C++ code and create a .clang-format file for you. You would probably only want to do this once though, so I don’t think it has much potential as a commercial product.

There are only two things I couldn’t get quite right in the formatting:

  1. I couldn’t get it to add a blank line after public, protected and private declarations. I fixed this with a quick Perl hack (see below).
  2. I couldn’t get it to indent continuation lines how I would like (ideally indented 1 or 2 spaces from the first line). It is a small price to pay and I am just putting up with it for now.

Perhaps there are options to do these and I just didn’t find them.

Here is the Windows .bat script I used to format all the C++ files in a folder.

for %%f in (*.h *.cpp *.inl) do (
clang-format.exe -i -style=file %%f
)

for %%f in (*.h) do (
clang-format.exe -i -style=file %%f
perl -p -i.bak -e "s/public:/public:\n/g" %%f
perl -p -i.bak -e "s/protected:/protected:\n/g" %%f
perl -p -i.bak -e "s/private:/private:\n/g" %%f
perl -p -i.bak -e "s/    Q_OBJECT/Q_OBJECT/g" %%f
)

del *.bak
del *.tmp

No doubt there is a more elegant way to do the Perl, but it works.

I now just run this batch periodically to keep my code beautiful and consistent.

A code pretty printer product idea

I use QtCreator for my C++ development IDE. It is very good. But it doesn’t always lay out my C++ code the way I want it to. In particular the refactoring operations mess up my white space. I want my code to look like:

void foo( int* x, int& y )

But it keeps changing it to:

void foo(int *x, int &y)

Grrrrrr.

So I am constantly battling with QtCreator to layout my code how I like it. There are plenty of C++ pretty printers around. I played with some of the leading ones using UniversalIndentGUI, but I couldn’t get any of them to layout my code quite how I wanted. Maybe they could have done it, but I got fed up with fiddling with the settings.

What I need is a code pretty printer that I can configure to layout my code exactly how I want without me having to tweak 100 settings.

Ideally I want a code pretty printer that I can train. So I just point it at a few files of my code that are laid out how I want and it works out all my preferences (where to put braces, how to indent case statements, where to put the * for a pointer declaration etc) and can then apply them to any other code. It wouldn’t need a GUI. Or perhaps just enough to select the training files and then preview the results on other files.

I have no idea if this is a viable product idea. But I would pay $100 for it, if it worked well. Perhaps bigger software companies would pay a lot more? Or maybe something like this already exists and I just don’t know about it?

SQL Pretty Printer

I did some consulting a few months back for James Wang of SQL Pretty Printer, concentrating mainly on marketing and usability. James was kind enough to send me an update on his progress and allow me to reproduce it here:

I launched my product SQL Pretty Printer several years ago, but I wasn’t satisfied with sales. So I contacted Andy to do some consulting about my product and website.

After several rounds of questions, Andy looked at my product and website and did some research. Andy’s final report is easy to read and understand, and lists about 100 actionable points about my product and website. After that, it took me about 3-4 weeks to apply this advice with the help of Andy. 3 months later, I’m really satisfied with the result: the downloads have increased 36%, and the sales increased 25%.

So my conclusion is if you have a product, and want to sell more, Andy is the person you need to approach.

SQL Pretty Printer is a good example of focussing on a single, well-defined problem and really nailing it, allowing you to turn this:

ugly sql

Into this:

pretty sql

SQL Pretty Printer has a wide range of formatting options and comes as a standalone Windows app, Visual Studio add-in, SSMS add-in and even an API for integration into your own app. If you have to work with less than beautiful SQL I recommend you try it.