clang-format Style Options

(事情によりclang-format-6.0縛りプレイ中)
(色々試せてないので間違ってらごめんなさい)

参考資料

releases.llvm.org

clang.llvm.org

algo13.net

yasuharu519.hatenablog.com


Style Options 詳細(v6基準)

BasedOnStyle (strig)

基本スタイルの指定。 LLVM,Google,Chrominum,Mozilla,WebKitなどある。

基本スタイルの各設定を知りたければdumpできる。

$ clang-format -style=llvm -dump-config > .clang-format-llvm
Language (LanguageKind)

対象としているフォーマットスタイルの言語

None, Cpp, Java, JavaScript, Proto

AccessModifierOffset (int)

アクセス修飾子(e.g. public:)のインデント位置

クラス内ではIndentWidthの値で既にインデントされているので、それを含めて値を指定する

// AccessModifierOffset: -4
// IndentWidth: 4
class Sample
{
public:
    void hoge();
};
AlignAfterOpenBracket (BracketAlignmentStyle)

引数の整列スタイルを指定

// Align
someLongFunction(argument1
                 argument2);

// DontAlign
someLongFunction(argument1,
    argument2);

// AlwaysBreak
someLongfunction(
    argument1, argument2);
AlignConsecutiveAssignments (bool)

変数への代入が連続したときに=で整列

int aaaa = 12;
int b    = 23;
int ccc  = 23;
AlignConsecutiveDeclarations (bool)

連続する行の宣言を揃える

int         aaaa = 12;
float       b = 23;
std::string ccc = 23;
AlignEscapedNewlines (EscapedNewlineAlignmentStyle)

エスケープされた改行の位置指定

// DontAlign
#define A \
  int aaaa; \
  int b; \
  int dddddddddd;

// Left (or true)
#define A   \
  int aaaa; \
  int b;    \
  int dddddddddd;

// Right (or false), ColumnLimitに配置される
#define A                  \
  int aaaa;                \
  int b;                   \
  int dddddddddd;

=> 古いverだとbool指定だったみたい

AlignOperands (bool)

水平方向に二項演算子三項演算子を揃える

int aaa = bbbbbbbbbbbbbbb +
          ccccccccccccccc;

=> v12だと引数が(OperandAlignmentStyle)になりDontAlign,Align,AliginAfterOperatorなど増える。

// v12
// Align
int aaa = bbbbbbbbbbbbbbb +
          ccccccccccccccc;
          
// AlignAfterOperator
int aaa = bbbbbbbbbbbbbbb
        + ccccccccccccccc;
AlignTrailingComments(bool)

末尾のコメント行を揃える

// true
int a;     // My comment a
int b = 2; // comment b
AllowAllParametersOfDeclarationOnNextLine (bool)

次の行に関数宣言のすべてのパラメータを置く、BinPackParametersfalseでも。

// true
void myFunction(
    int a, int b, int c, int d, int e);

// false
void myFunction(int a,
                int b,
                int c,
                int d,
                int e);
AllowShortBlocksOnASingleLine (bool)

単一の行に簡単なブレース文をまとめる

例えば、 if (a) { return; }

AllowShortCaseLabelsOnASingleLine (bool)

短いケースラベルを単一行にまとめる

AllowShortFunctionsOnASingleLine (ShortFunctionStyle)

int f() { return 0; }を単一行にするか。

  • None しない
  • InlineOnly class内で定義された関数だけ
  • Inline class内で定義された関数と空の関数だけ
  • Empty 空の関数だけ
  • All 全て単一行にする
AllowShortIfStatementsOnASingleLine (bool)

trueの時、単一行のif (a) return; をキープ

AllowShortLoopsOnASingleLine (bool)

trueの時、単一行のwhile (true) continue;をキープ

AlwaysBreakAfterDefinitionReturnType

廃止
関数の戻り値宣言のスタイル

=> AlwasyBreakAfterReturnTypeを使う。

AlwaysBreakAfterReturnType (ReturnTypeBreakingStyle)

関数宣言の戻り値のスタイル、戻り値の後に改行を入れるか

None,All,TopLevel,AllDefinitions,TopLevelDefinitionsがある。

// None
class A {
  int f() { return 0; };
};
int f();
int f() { return 1; }

// TopLevel
class A {
  int f() { return 0; };
};
int
f();
int
f() {
  return 1;
}
AlwaysBreakBeforeMultilineStrings (bool)

複数行のリテラル文字列の前で改行するか

// true
aaaa =
    "bbbb"
    "cccc";

// false
aaaa = "bbbb"
       "cccc";
AlwaysBreakTemplateDeclarations (bool)

テンプレート宣言template<...>の後に改行するか

BinPackArguments (bool)

関数呼び出しの引数を1行にまとめるか

// true
void f() {
  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
}

// false
void f() {
  f(aaaaaaaaaaaaaaaaaaaa,
    aaaaaaaaaaaaaaaaaaaa,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
}
BinPackParameters (bool)

関数宣言や関数定義のパラメータを一行にまとめるか

// true
void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}

// false
void f(int aaaaaaaaaaaaaaaaaaaa,
       int aaaaaaaaaaaaaaaaaaaa,
       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
BraceWrapping (BraceWrappingFlags)

{}のスタイル(改行を入れるか)を個別にネストして設定する、有効にするにはBreakBeforeBracesCustomにする必要がある

# Example of usage:
BreakBeforeBraces: Custom
BraceWrapping:
  AfterEnum: true
  AfterStruct: false
  SplitEmptyFunction: false
AfterClass (bool)

クラスの後に改行を入れるか

// true
class foo
{};

// false
class foo {};
AfterControlStatement (bool)

制御文の後 (if/for/while/switch, ...)

AfterEnum (bool)

enumの後

AfterFunction (bool)

関数の後

AfterNamespace (bool)

namespaceの後

AfterObjCDeclaration (bool)

ObjC宣言(@autoreleasepool, interfaces, ...)の後

AfterStruct (bool)

structの後

AfterUnion (bool)

unionの後

AfterExternBlock (bool)

externブロックをラップする{}を分けるか

// true
extern "C"
{
  int foo();
}

// false
extern "C" {
int foo();
}
BeforeCatch (bool)

catchの前

BeforeElse (bool)

elseの前

IndentBraces

?

SplitEmptyFunction (bool)

関数の後の空の{}を分けるか

// true
int f()
{
}

// false
int f()
{}
SplitEmptyRecord (bool)

空のレコード(e.g. class, struct or union)の{}を分けるか

SplitEmptyNamespace (bool)

空のnamespaceの{}を分けるか

BreakBeforeBinaryOperators (BinaryOperatorStyle)

二項演算子の折り返しスタイル

// None
LooooooongType loooooooooooooooooongVariable =
    someLooooooooooooongFunction();

bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
                 ccccccccccccccccccccccccccccccccc;

// NonAssignment
LooooooongType loooooooooooooooooongVariable =
    someLooooooooooooongFunction();

bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                    > ccccccccccccccccccccccccccccccccc;
BreakBeforeBraces (BraceBreakingStyle)

{}のスタイルを指定

  • Attach 常にコンテキストにくっつける
  • Linux 関数、名前空間、クラス定義の{}前で改行
  • Mozilla enum、関数、レコード(class, struct or union)で改行
  • Stroustrup 関数定義、catch、elseで改行を入れる
  • Allman 全ての{}前に改行を入れる
  • GNU 全ての{}前に改行を入れる、クラス以外の関数などの定義文の{}にインデントを加える
  • Webkit Attach風、ただし関数の前に改行を入れる
  • Custom BraceWrappingで個別設定
BreakBeforeInheritanceComma (bool)

クラス定義の:,,で改行を加えるか

// true
class MyClass
    : public X
    , public Y {
};

// false
class MyClass : public X, public Y {
};
BreakBeforeTernaryOperators (bool)

三項演算子の前に改行を入れるか

// true
veryVeryVeryVeryLongDescription
    ? firstValue
    : SecondValueVeryVeryVeryVeryLong;

// false
veryVeryVeryVeryLongDescription ?
    firstValue :
    SecondValueVeryVeryVeryVeryLong;
BreakConstructorInitializersBeforeComma (bool)

廃止
コンストラクタ初期化の,前で改行入れるか

BreakConstructorInitializers (BreakConstructorInitializersStyle)

コンストラクタ初期化のスタイル、,前で改行するか

// BeforeColon
Constructor()
    : initializer1(),
      initializer2()

// BeforeComma
Constructor()
    : initializer1()
    , initializer2()

// AfterColon
Constructor() : 
    initializer1(),
    initializer2()
BreakStringLiterals (bool)

フォーマット時に文字列リテラルを改行で調整するか

// true
const char* x = "veryVeryVeryVeryVeryVe"
                "ryVeryVeryVeryVeryVery"
                "VeryLongString";

// false
const char* x =
  "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
ColumnLimit (unsigned)

行の長さ上限。0の場合は上限なし

CommentPragmas (std::string)

行分割や変更などされたくない、特別な意味を持つコメントを記述するための正規表現。初期値^ IWYU pragma:CommentPragmas: '\*doxygenコメントを無視

CompactNamespaces (bool)

namespaceをコンパクトに収めるか

// true
namespace Foo { namespace Bar {
}}
ConstructorInitializerAllOnOneLineOrOnePerLine (bool)

コンストラクタ初期化子が行に収まらない場合は改行するか

ConstructorInitializerIndentWidth (unsigned)

コンストラクタ初期化子リストのインデント数

ContinuationIndentWidth (unsigned)

継続する行のインデント数

// ContinuationIndentWidth: 2の場合
int i =        // VeryVeryLongComment
  longFunction(   // Again a long comment
    arg);
Cpp11BracedListStyle (bool)

{}リストの扱いをC++11に適したスタイルにする

{}の端にスペースを入れない、閉じ}の前に改行を入れない、など

DerivePointerAlignment (bool)

引数の*,&の位置を自動判定で修正する PointerAlignmentはフォールバックとして使う(=自動判定できなかったときに使う)

DisableFormat (bool)

全ての書式設定を無効にする

ExperimentalAutoDetectBinPacking (bool)

自動的にビンパッキングする? 実験的なフラグなのでご利用は計画的に、みたいな

NOTE: This is an experimental flag, that might go away or be renamed. Do not use this in config files, etc. Use at your own risk.

FixNamespaceComments (bool)

namespaceにエンドコメントを追加する

// true:
namespace a {
foo();
} // namesapce a;

// false:
namespace a {
foo();
}
ForEachMacros (std::vector\<std::string>)

関数呼び出しではなく、foreachループのためのマクロだと認識させる

BOOST_FOREACHなどを関数認識して、改行など改変を入れないよう指定する、たぶん

ForEachMacros:   
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
IncludeBlocks (IncludeBlocksStyle)

#includeブロックの分けてある部分をどうするか

  • Preserve分けたまま
  • Merge ひっつけて一塊にする
  • Regroup 部門別に再グループ化、IncludeCategoriesの値を使う
IncludeCategories (std::vector\<IncludeCategory>)

#includeのグループ化、順序化するための正規表現

IncludeIsMainRegex (std::string)

#includeが「メイン」インクルードかを推測するためのセフィックスの正規表現を指定する(インクルードのカテゴリを分けるときにメインかを推測するため)

例えば(_test)?$に設定している場合、a.hは、a.cca_test.ccの両方で「メイン」と見なされる

# example style of Google
IncludeCategories: 
  - Regex:           '^<ext/.*\.h>'
    Priority:        2
  - Regex:           '^<.*\.h>'
    Priority:        1
  - Regex:           '^<.*'
    Priority:        2
  - Regex:           '.*'
    Priority:        3

IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels (bool)

switch/case/label文でインデントするか

IndentPPDirectives (PPDirectiveIndentStyle)

プリプロセッサのスタイル

// None
#if FOO
#if BAR
#include <foo>
#endif
#endif

// AfterHash
#if FOO
#  if BAR
#    include <foo>
#  endif
#endif
IndentWidth (unsigned)

インデント数

IndentWrappedFunctionNames (bool)

関数の宣言か定義で、型名の後に改行された場合インデントするか

KeepEmptyLinesAtTheStartOfBlocks (bool)

ブロック最初の空行を残すか

MacroBlockBegin (std::string)

ブロックを開始するマクロの正規表現

MacroBlockEnd: (std::string)

ブロックを終了するマクロの正規表現

MaxEmptyLinesToKeep (unsigned)

連続する空行の保持数、それ以上は削除

NamespaceIndentation (NamespaceIndentationKind)

namespaceのインデントスタイル

// None (しない)
namespace out {
int i;
namespace in {
int i;
}
}

// Inner (内側の名前空間だけインデント)
namespace out {
int i;
namespace in {
  int i;
}
}

// All (全部インデント)
namespace out {
  int i;
  namespace in {
    int i;
  }
}
ObjCBlockIndentWidth (unsigned)

Objective-Cのインデント数

ObjCSpaceAfterProperty (bool)

@propertyの後にスペースを追加する。

@property(readonly)の代わりに@property (readonly)を使用する。

ObjCSpaceBeforeProtocolList (bool)

プロトコルリストの前にスペースを追加。

Foo<Protocol>の代わりにFoo <Protocol>を使用する。

PenaltyBreakAssignment (unsigned)

代入演算子のペナルティ

PenaltyBreakBeforeFirstCallParameter (unsigned)

call(のペナルティ

PenaltyBreakComment (unsigned)

改行のペナルティ

PenaltyBreakFirstLessLess (unsigned)

<<のペナルティ

PenaltyBreakString (unsigned)

文字列のペナルティ

PenaltyExcessCharacter (unsigned)

列の制限外の文字に対するペナルティ

PenaltyReturnTypeOnItsOwnLine (unsigned)

関数の戻り値の型をそれ自体の行に置くことに対するペナルティ

=> ドキュメントにはペナルティが何か明確な説明がない。 ある制限に遭遇、または複数が重なった場合、例外にするのか、どちらを優先する重み付け、みたいな。以下参照。

stackoverflow.com

PointerAlignment (PointerAlignmentStyle)

ポインタ*、参照&をどの位置で揃えるか

// Left
int* a;

// Right
int *a;

// Middle
int * a;
RawStringFormats (std::vector\<RawStringFormat>)

?

ReflowComments (bool)

コメントをリフロー(再流し込み)するか

true
// VeryVeryVeryVeryLongComment with plenty of
// information
/* second VeryVeryVeryVeryLongComment with plenty of
 * information */

false
// VeryVeryVeryVeryLongComment with plenty of information
/* second VeryVeryVeryVeryLongComment with plenty of information */
SortIncludes (bool)

#includeをソートするか

SortUsingDeclarations (bool)

using宣言をソートするか

SpaceAfterCStyleCast (bool)

Cスタイルのキャスト後のスペース

// true
(int) i;

// false
(int)i;

=> v6のマニュアルが逆に書いてる、基本Space~trueで入れる、falseなら入れない

SpaceAfterTemplateKeyword (bool)

<template>の後のスペース

// true
template <int> void foo();

// false
template<int> void foo();
SpaceBeforeAssignmentOperators (bool)

代入演算子の後のスペース

// true
int a = 5;
a += 42

// false
int a=5;
a+=42;
SpaceBeforeParens (SpaceBeforeParensOptions)

開始括弧(の前のスペース

// Never  (入れない)
void f() {
  if(true) {
    f();
  }
}

// ControlStatements
//        (制御文(if/for/while...)と開始括弧の間に入れる)
void f() {
  if (true) {
    f();
  }
}

// Always  (開始括弧の前にスペースを入れる)
void f () {
  if (true) {
    f ();
  }
}
SpaceInEmptyParentheses (bool)

空括弧内のスペース

// true
void f ( ) {
  int x[] = {foo( ), bar( )};
}

// false
void f () {
  int x[] = {foo(), bar()};
}
SpacesBeforeTrailingComments (unsigned)

コメントの前のスペース幅

// SpacesBeforeTrailingComments: 3
void f() {   // space 3
}            // end of f
SpacesInAngles (bool)

山括弧<>内の前後スペース

// true
static_cast< int >(arg);
std::function< void(int) > fct;

// false
static_cast<int>(arg);
std::function<void(int)> fct;
SpacesInContainerLiterals (bool)

コンテナリテラル(e.g ObjC, Javascript配列, dict) 内部にスペースを入れるか

// true
var arr = [ 1, 2, 3 ];
f({a : 1, b : 2, c : 3});

// false
var arr = [1, 2, 3];
f({a: 1, b: 2, c: 3});
SpacesInCStyleCastParentheses (bool)

Cスタイルのキャスト()内にスペースを入れるか

// true
x = ( int32 )y

// false
x = (int32)y
SpacesInParentheses (bool)

()内にスペースを入れるか

// true
t f( Delete & ) = delete;

// false
t f(Delete &) & = delete;
SpacesInSquareBrackets (false)

[]内にスペースを入れるか

// true
int a[ 5 ];

// false
int a[5];
Standard (LanguageStandard)

標準スタイルの指定、指定した規格の構文を使う

  • Cpp03 C++03互換の構文を使う
  • Cpp11 C++11の機能を使う
  • Auto 自動検出

Cpp11指定するとA<A<int> >の代わりにA<A<int>>を使う、など

TabWidth (unsinged)

タブ幅

UseTab (UseTabStyle)

タブを使うかのスタイル

  • Never 使わない
  • ForIndentation インデントのみにタブを使う
  • AlWays 可能な限りタブを使う

資料: googleスタイル

$ clang-format --version
clang-format version 6.0.1-0+deb8u1 (tags/RELEASE_601/final)

$ clang-format -style=google -dump-config > google.yaml

出力したyamlファイル

---
Language:        Cpp
# BasedOnStyle:  Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands:   true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:   
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  AfterExternBlock: false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     80
CommentPragmas:  '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:   
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
IncludeBlocks:   Preserve
IncludeCategories: 
  - Regex:           '^<ext/.*\.h>'
    Priority:        2
  - Regex:           '^<.*\.h>'
    Priority:        1
  - Regex:           '^<.*'
    Priority:        2
  - Regex:           '.*'
    Priority:        3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth:     2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
RawStringFormats: 
  - Delimiter:       pb
    Language:        TextProto
    BasedOnStyle:    google
ReflowComments:  true
SortIncludes:    true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles:  false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard:        Auto
TabWidth:        8
UseTab:          Never
...