Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow clang-format to format empty classes/structs on one line?

Having the following structs definitions:

struct city
{
};
struct country
{
};

I would like clang-format to format it for me like

struct city {};
struct country {};

How can I achieve this?

I can see a lot of options like AllowShortBlocksOnASingleLine, AllowShortFunctionsOnASingleLine or AllowShortIfStatementsOnASingleLine but no AllowShortClassDefinitionsOnASingleLine (or similar).

like image 844
Patryk Avatar asked Dec 12 '16 14:12

Patryk


1 Answers

As of clang-format 12, the individual functionality that you required is, unfortunately, missing.

That is, if you want an empty struct / class to be in a single line, then you have to accept that the opening curly brace { always stays in the same line as struct or class. To do so, set

BreakBeforeBraces: Custom
BraceWrapping:
  AfterClass: false

Then you will have

class A {};

class B {
  void foo() {}
};

If you want to achieve something like

class A {};

class B 
{
  void foo() {}
};

Then I am afraid clang-format cannot do that as far as I know.


I will discuss some related options below.

First, assume we have set

BreakBeforeBraces: Custom

Without this, all the options that follow are ignored.

Then,

BraceWrapping:
  AfterClass: false

would result in

class Foo {
    // data members and member functions
};

In contrast,

BraceWrapping:
  AfterClass: true

would lead to

class Foo 
{
    // data members and member functions
};

Now, given AfterClass is set to true, then SplitEmptyRecord determines whether an empty class will be split to two lines.

BraceWrapping:
  SplitEmptyRecord: false

would result in

class EmptyClass
{};

while

  SplitEmptyRecord: true

would give you

class EmptyClass
{
};

Sadly, none of these specifically address your problem.

For reference, see Clang-Format Style Options

like image 108
aafulei Avatar answered Oct 27 '22 14:10

aafulei