ClangFormatStyleOptions.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. ==========================
  2. Clang-Format Style Options
  3. ==========================
  4. :doc:`ClangFormatStyleOptions` describes configurable formatting style options
  5. supported by :doc:`LibFormat` and :doc:`ClangFormat`.
  6. When using :program:`clang-format` command line utility or
  7. ``clang::format::reformat(...)`` functions from code, one can either use one of
  8. the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit) or create a
  9. custom style by configuring specific style options.
  10. Configuring Style with clang-format
  11. ===================================
  12. :program:`clang-format` supports two ways to provide custom style options:
  13. directly specify style configuration in the ``-style=`` command line option or
  14. use ``-style=file`` and put style configuration in the ``.clang-format`` or
  15. ``_clang-format`` file in the project directory.
  16. When using ``-style=file``, :program:`clang-format` for each input file will
  17. try to find the ``.clang-format`` file located in the closest parent directory
  18. of the input file. When the standard input is used, the search is started from
  19. the current directory.
  20. The ``.clang-format`` file uses YAML format:
  21. .. code-block:: yaml
  22. key1: value1
  23. key2: value2
  24. # A comment.
  25. ...
  26. The configuration file can consist of several sections each having different
  27. ``Language:`` parameter denoting the programming language this section of the
  28. configuration is targeted at. See the description of the **Language** option
  29. below for the list of supported languages. The first section may have no
  30. language set, it will set the default style options for all lanugages.
  31. Configuration sections for specific language will override options set in the
  32. default section.
  33. When :program:`clang-format` formats a file, it auto-detects the language using
  34. the file name. When formatting standard input or a file that doesn't have the
  35. extension corresponding to its language, ``-assume-filename=`` option can be
  36. used to override the file name :program:`clang-format` uses to detect the
  37. language.
  38. An example of a configuration file for multiple languages:
  39. .. code-block:: yaml
  40. ---
  41. # We'll use defaults from the LLVM style, but with 4 columns indentation.
  42. BasedOnStyle: LLVM
  43. IndentWidth: 4
  44. ---
  45. Language: Cpp
  46. # Force pointers to the type for C++.
  47. DerivePointerAlignment: false
  48. PointerAlignment: Left
  49. ---
  50. Language: JavaScript
  51. # Use 100 columns for JS.
  52. ColumnLimit: 100
  53. ---
  54. Language: Proto
  55. # Don't format .proto files.
  56. DisableFormat: true
  57. ...
  58. An easy way to get a valid ``.clang-format`` file containing all configuration
  59. options of a certain predefined style is:
  60. .. code-block:: console
  61. clang-format -style=llvm -dump-config > .clang-format
  62. When specifying configuration in the ``-style=`` option, the same configuration
  63. is applied for all input files. The format of the configuration is:
  64. .. code-block:: console
  65. -style='{key1: value1, key2: value2, ...}'
  66. Disabling Formatting on a Piece of Code
  67. =======================================
  68. Clang-format understands also special comments that switch formatting in a
  69. delimited range. The code between a comment ``// clang-format off`` or
  70. ``/* clang-format off */`` up to a comment ``// clang-format on`` or
  71. ``/* clang-format on */`` will not be formatted. The comments themselves
  72. will be formatted (aligned) normally.
  73. .. code-block:: c++
  74. int formatted_code;
  75. // clang-format off
  76. void unformatted_code ;
  77. // clang-format on
  78. void formatted_code_again;
  79. Configuring Style in Code
  80. =========================
  81. When using ``clang::format::reformat(...)`` functions, the format is specified
  82. by supplying the `clang::format::FormatStyle
  83. <http://clang.llvm.org/doxygen/structclang_1_1format_1_1FormatStyle.html>`_
  84. structure.
  85. Configurable Format Style Options
  86. =================================
  87. This section lists the supported style options. Value type is specified for
  88. each option. For enumeration types possible values are specified both as a C++
  89. enumeration member (with a prefix, e.g. ``LS_Auto``), and as a value usable in
  90. the configuration (without a prefix: ``Auto``).
  91. **BasedOnStyle** (``string``)
  92. The style used for all options not specifically set in the configuration.
  93. This option is supported only in the :program:`clang-format` configuration
  94. (both within ``-style='{...}'`` and the ``.clang-format`` file).
  95. Possible values:
  96. * ``LLVM``
  97. A style complying with the `LLVM coding standards
  98. <http://llvm.org/docs/CodingStandards.html>`_
  99. * ``Google``
  100. A style complying with `Google's C++ style guide
  101. <http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml>`_
  102. * ``Chromium``
  103. A style complying with `Chromium's style guide
  104. <http://www.chromium.org/developers/coding-style>`_
  105. * ``Mozilla``
  106. A style complying with `Mozilla's style guide
  107. <https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style>`_
  108. * ``WebKit``
  109. A style complying with `WebKit's style guide
  110. <http://www.webkit.org/coding/coding-style.html>`_
  111. .. START_FORMAT_STYLE_OPTIONS
  112. **AccessModifierOffset** (``int``)
  113. The extra indent or outdent of access modifiers, e.g. ``public:``.
  114. **AlignAfterOpenBracket** (``bool``)
  115. If ``true``, horizontally aligns arguments after an open bracket.
  116. This applies to round brackets (parentheses), angle brackets and square
  117. brackets. This will result in formattings like
  118. \code
  119. someLongFunction(argument1,
  120. argument2);
  121. \endcode
  122. **AlignConsecutiveAssignments** (``bool``)
  123. If ``true``, aligns consecutive assignments.
  124. This will align the assignment operators of consecutive lines. This
  125. will result in formattings like
  126. \code
  127. int aaaa = 12;
  128. int b = 23;
  129. int ccc = 23;
  130. \endcode
  131. **AlignEscapedNewlinesLeft** (``bool``)
  132. If ``true``, aligns escaped newlines as far left as possible.
  133. Otherwise puts them into the right-most column.
  134. **AlignOperands** (``bool``)
  135. If ``true``, horizontally align operands of binary and ternary
  136. expressions.
  137. **AlignTrailingComments** (``bool``)
  138. If ``true``, aligns trailing comments.
  139. **AllowAllParametersOfDeclarationOnNextLine** (``bool``)
  140. Allow putting all parameters of a function declaration onto
  141. the next line even if ``BinPackParameters`` is ``false``.
  142. **AllowShortBlocksOnASingleLine** (``bool``)
  143. Allows contracting simple braced statements to a single line.
  144. E.g., this allows ``if (a) { return; }`` to be put on a single line.
  145. **AllowShortCaseLabelsOnASingleLine** (``bool``)
  146. If ``true``, short case labels will be contracted to a single line.
  147. **AllowShortFunctionsOnASingleLine** (``ShortFunctionStyle``)
  148. Dependent on the value, ``int f() { return 0; }`` can be put
  149. on a single line.
  150. Possible values:
  151. * ``SFS_None`` (in configuration: ``None``)
  152. Never merge functions into a single line.
  153. * ``SFS_Empty`` (in configuration: ``Empty``)
  154. Only merge empty functions.
  155. * ``SFS_Inline`` (in configuration: ``Inline``)
  156. Only merge functions defined inside a class. Implies "empty".
  157. * ``SFS_All`` (in configuration: ``All``)
  158. Merge all functions fitting on a single line.
  159. **AllowShortIfStatementsOnASingleLine** (``bool``)
  160. If ``true``, ``if (a) return;`` can be put on a single
  161. line.
  162. **AllowShortLoopsOnASingleLine** (``bool``)
  163. If ``true``, ``while (true) continue;`` can be put on a
  164. single line.
  165. **AlwaysBreakAfterDefinitionReturnType** (``DefinitionReturnTypeBreakingStyle``)
  166. The function definition return type breaking style to use.
  167. Possible values:
  168. * ``DRTBS_None`` (in configuration: ``None``)
  169. Break after return type automatically.
  170. ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
  171. * ``DRTBS_All`` (in configuration: ``All``)
  172. Always break after the return type.
  173. * ``DRTBS_TopLevel`` (in configuration: ``TopLevel``)
  174. Always break after the return types of top level functions.
  175. **AlwaysBreakBeforeMultilineStrings** (``bool``)
  176. If ``true``, always break before multiline string literals.
  177. This flag is mean to make cases where there are multiple multiline strings
  178. in a file look more consistent. Thus, it will only take effect if wrapping
  179. the string at that point leads to it being indented
  180. ``ContinuationIndentWidth`` spaces from the start of the line.
  181. **AlwaysBreakTemplateDeclarations** (``bool``)
  182. If ``true``, always break after the ``template<...>`` of a
  183. template declaration.
  184. **BinPackArguments** (``bool``)
  185. If ``false``, a function call's arguments will either be all on the
  186. same line or will have one line each.
  187. **BinPackParameters** (``bool``)
  188. If ``false``, a function declaration's or function definition's
  189. parameters will either all be on the same line or will have one line each.
  190. **BreakBeforeBinaryOperators** (``BinaryOperatorStyle``)
  191. The way to wrap binary operators.
  192. Possible values:
  193. * ``BOS_None`` (in configuration: ``None``)
  194. Break after operators.
  195. * ``BOS_NonAssignment`` (in configuration: ``NonAssignment``)
  196. Break before operators that aren't assignments.
  197. * ``BOS_All`` (in configuration: ``All``)
  198. Break before operators.
  199. **BreakBeforeBraces** (``BraceBreakingStyle``)
  200. The brace breaking style to use.
  201. Possible values:
  202. * ``BS_Attach`` (in configuration: ``Attach``)
  203. Always attach braces to surrounding context.
  204. * ``BS_Linux`` (in configuration: ``Linux``)
  205. Like ``Attach``, but break before braces on function, namespace and
  206. class definitions.
  207. * ``BS_Mozilla`` (in configuration: ``Mozilla``)
  208. Like ``Attach``, but break before braces on enum, function, and record
  209. definitions.
  210. * ``BS_Stroustrup`` (in configuration: ``Stroustrup``)
  211. Like ``Attach``, but break before function definitions, and 'else'.
  212. * ``BS_Allman`` (in configuration: ``Allman``)
  213. Always break before braces.
  214. * ``BS_GNU`` (in configuration: ``GNU``)
  215. Always break before braces and add an extra level of indentation to
  216. braces of control statements, not to those of class, function
  217. or other definitions.
  218. **BreakBeforeTernaryOperators** (``bool``)
  219. If ``true``, ternary operators will be placed after line breaks.
  220. **BreakConstructorInitializersBeforeComma** (``bool``)
  221. Always break constructor initializers before commas and align
  222. the commas with the colon.
  223. **ColumnLimit** (``unsigned``)
  224. The column limit.
  225. A column limit of ``0`` means that there is no column limit. In this case,
  226. clang-format will respect the input's line breaking decisions within
  227. statements unless they contradict other rules.
  228. **CommentPragmas** (``std::string``)
  229. A regular expression that describes comments with special meaning,
  230. which should not be split into lines or otherwise changed.
  231. **ConstructorInitializerAllOnOneLineOrOnePerLine** (``bool``)
  232. If the constructor initializers don't fit on a line, put each
  233. initializer on its own line.
  234. **ConstructorInitializerIndentWidth** (``unsigned``)
  235. The number of characters to use for indentation of constructor
  236. initializer lists.
  237. **ContinuationIndentWidth** (``unsigned``)
  238. Indent width for line continuations.
  239. **Cpp11BracedListStyle** (``bool``)
  240. If ``true``, format braced lists as best suited for C++11 braced
  241. lists.
  242. Important differences:
  243. - No spaces inside the braced list.
  244. - No line break before the closing brace.
  245. - Indentation with the continuation indent, not with the block indent.
  246. Fundamentally, C++11 braced lists are formatted exactly like function
  247. calls would be formatted in their place. If the braced list follows a name
  248. (e.g. a type or variable name), clang-format formats as if the ``{}`` were
  249. the parentheses of a function call with that name. If there is no name,
  250. a zero-length name is assumed.
  251. **DerivePointerAlignment** (``bool``)
  252. If ``true``, analyze the formatted file for the most common
  253. alignment of & and \*. ``PointerAlignment`` is then used only as fallback.
  254. **DisableFormat** (``bool``)
  255. Disables formatting completely.
  256. **ExperimentalAutoDetectBinPacking** (``bool``)
  257. If ``true``, clang-format detects whether function calls and
  258. definitions are formatted with one parameter per line.
  259. Each call can be bin-packed, one-per-line or inconclusive. If it is
  260. inconclusive, e.g. completely on one line, but a decision needs to be
  261. made, clang-format analyzes whether there are other bin-packed cases in
  262. the input file and act accordingly.
  263. NOTE: This is an experimental flag, that might go away or be renamed. Do
  264. not use this in config files, etc. Use at your own risk.
  265. **ForEachMacros** (``std::vector<std::string>``)
  266. A vector of macros that should be interpreted as foreach loops
  267. instead of as function calls.
  268. These are expected to be macros of the form:
  269. \code
  270. FOREACH(<variable-declaration>, ...)
  271. <loop-body>
  272. \endcode
  273. For example: BOOST_FOREACH.
  274. **IndentCaseLabels** (``bool``)
  275. Indent case labels one level from the switch statement.
  276. When ``false``, use the same indentation level as for the switch statement.
  277. Switch statement body is always indented one level more than case labels.
  278. **IndentWidth** (``unsigned``)
  279. The number of columns to use for indentation.
  280. **IndentWrappedFunctionNames** (``bool``)
  281. Indent if a function definition or declaration is wrapped after the
  282. type.
  283. **KeepEmptyLinesAtTheStartOfBlocks** (``bool``)
  284. If true, empty lines at the start of blocks are kept.
  285. **Language** (``LanguageKind``)
  286. Language, this format style is targeted at.
  287. Possible values:
  288. * ``LK_None`` (in configuration: ``None``)
  289. Do not use.
  290. * ``LK_Cpp`` (in configuration: ``Cpp``)
  291. Should be used for C, C++, ObjectiveC, ObjectiveC++.
  292. * ``LK_Java`` (in configuration: ``Java``)
  293. Should be used for Java.
  294. * ``LK_JavaScript`` (in configuration: ``JavaScript``)
  295. Should be used for JavaScript.
  296. * ``LK_Proto`` (in configuration: ``Proto``)
  297. Should be used for Protocol Buffers
  298. (https://developers.google.com/protocol-buffers/).
  299. **MacroBlockBegin** (``std::string``)
  300. A regular expression matching macros that start a block.
  301. **MacroBlockEnd** (``std::string``)
  302. A regular expression matching macros that end a block.
  303. **MaxEmptyLinesToKeep** (``unsigned``)
  304. The maximum number of consecutive empty lines to keep.
  305. **NamespaceIndentation** (``NamespaceIndentationKind``)
  306. The indentation used for namespaces.
  307. Possible values:
  308. * ``NI_None`` (in configuration: ``None``)
  309. Don't indent in namespaces.
  310. * ``NI_Inner`` (in configuration: ``Inner``)
  311. Indent only in inner namespaces (nested in other namespaces).
  312. * ``NI_All`` (in configuration: ``All``)
  313. Indent in all namespaces.
  314. **ObjCBlockIndentWidth** (``unsigned``)
  315. The number of characters to use for indentation of ObjC blocks.
  316. **ObjCSpaceAfterProperty** (``bool``)
  317. Add a space after ``@property`` in Objective-C, i.e. use
  318. ``\@property (readonly)`` instead of ``\@property(readonly)``.
  319. **ObjCSpaceBeforeProtocolList** (``bool``)
  320. Add a space in front of an Objective-C protocol list, i.e. use
  321. ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
  322. **PenaltyBreakBeforeFirstCallParameter** (``unsigned``)
  323. The penalty for breaking a function call after "call(".
  324. **PenaltyBreakComment** (``unsigned``)
  325. The penalty for each line break introduced inside a comment.
  326. **PenaltyBreakFirstLessLess** (``unsigned``)
  327. The penalty for breaking before the first ``<<``.
  328. **PenaltyBreakString** (``unsigned``)
  329. The penalty for each line break introduced inside a string literal.
  330. **PenaltyExcessCharacter** (``unsigned``)
  331. The penalty for each character outside of the column limit.
  332. **PenaltyReturnTypeOnItsOwnLine** (``unsigned``)
  333. Penalty for putting the return type of a function onto its own
  334. line.
  335. **PointerAlignment** (``PointerAlignmentStyle``)
  336. Pointer and reference alignment style.
  337. Possible values:
  338. * ``PAS_Left`` (in configuration: ``Left``)
  339. Align pointer to the left.
  340. * ``PAS_Right`` (in configuration: ``Right``)
  341. Align pointer to the right.
  342. * ``PAS_Middle`` (in configuration: ``Middle``)
  343. Align pointer in the middle.
  344. **SpaceAfterCStyleCast** (``bool``)
  345. If ``true``, a space may be inserted after C style casts.
  346. **SpaceBeforeAssignmentOperators** (``bool``)
  347. If ``false``, spaces will be removed before assignment operators.
  348. **SpaceBeforeParens** (``SpaceBeforeParensOptions``)
  349. Defines in which cases to put a space before opening parentheses.
  350. Possible values:
  351. * ``SBPO_Never`` (in configuration: ``Never``)
  352. Never put a space before opening parentheses.
  353. * ``SBPO_ControlStatements`` (in configuration: ``ControlStatements``)
  354. Put a space before opening parentheses only after control statement
  355. keywords (``for/if/while...``).
  356. * ``SBPO_Always`` (in configuration: ``Always``)
  357. Always put a space before opening parentheses, except when it's
  358. prohibited by the syntax rules (in function-like macro definitions) or
  359. when determined by other style rules (after unary operators, opening
  360. parentheses, etc.)
  361. **SpaceInEmptyParentheses** (``bool``)
  362. If ``true``, spaces may be inserted into '()'.
  363. **SpacesBeforeTrailingComments** (``unsigned``)
  364. The number of spaces before trailing line comments
  365. (``//`` - comments).
  366. This does not affect trailing block comments (``/**/`` - comments) as those
  367. commonly have different usage patterns and a number of special cases.
  368. **SpacesInAngles** (``bool``)
  369. If ``true``, spaces will be inserted after '<' and before '>' in
  370. template argument lists
  371. **SpacesInCStyleCastParentheses** (``bool``)
  372. If ``true``, spaces may be inserted into C style casts.
  373. **SpacesInContainerLiterals** (``bool``)
  374. If ``true``, spaces are inserted inside container literals (e.g.
  375. ObjC and Javascript array and dict literals).
  376. **SpacesInParentheses** (``bool``)
  377. If ``true``, spaces will be inserted after '(' and before ')'.
  378. **SpacesInSquareBrackets** (``bool``)
  379. If ``true``, spaces will be inserted after '[' and before ']'.
  380. **Standard** (``LanguageStandard``)
  381. Format compatible with this standard, e.g. use
  382. ``A<A<int> >`` instead of ``A<A<int>>`` for LS_Cpp03.
  383. Possible values:
  384. * ``LS_Cpp03`` (in configuration: ``Cpp03``)
  385. Use C++03-compatible syntax.
  386. * ``LS_Cpp11`` (in configuration: ``Cpp11``)
  387. Use features of C++11 (e.g. ``A<A<int>>`` instead of
  388. ``A<A<int> >``).
  389. * ``LS_Auto`` (in configuration: ``Auto``)
  390. Automatic detection based on the input.
  391. **TabWidth** (``unsigned``)
  392. The number of columns used for tab stops.
  393. **UseTab** (``UseTabStyle``)
  394. The way to use tab characters in the resulting file.
  395. Possible values:
  396. * ``UT_Never`` (in configuration: ``Never``)
  397. Never use tab.
  398. * ``UT_ForIndentation`` (in configuration: ``ForIndentation``)
  399. Use tabs only for indentation.
  400. * ``UT_Always`` (in configuration: ``Always``)
  401. Use tabs whenever we need to fill whitespace that spans at least from
  402. one tab stop to the next one.
  403. .. END_FORMAT_STYLE_OPTIONS
  404. Examples
  405. ========
  406. A style similar to the `Linux Kernel style
  407. <https://www.kernel.org/doc/Documentation/CodingStyle>`_:
  408. .. code-block:: yaml
  409. BasedOnStyle: LLVM
  410. IndentWidth: 8
  411. UseTab: Always
  412. BreakBeforeBraces: Linux
  413. AllowShortIfStatementsOnASingleLine: false
  414. IndentCaseLabels: false
  415. The result is (imagine that tabs are used for indentation here):
  416. .. code-block:: c++
  417. void test()
  418. {
  419. switch (x) {
  420. case 0:
  421. case 1:
  422. do_something();
  423. break;
  424. case 2:
  425. do_something_else();
  426. break;
  427. default:
  428. break;
  429. }
  430. if (condition)
  431. do_something_completely_different();
  432. if (x == y) {
  433. q();
  434. } else if (x > y) {
  435. w();
  436. } else {
  437. r();
  438. }
  439. }
  440. A style similar to the default Visual Studio formatting style:
  441. .. code-block:: yaml
  442. UseTab: Never
  443. IndentWidth: 4
  444. BreakBeforeBraces: Allman
  445. AllowShortIfStatementsOnASingleLine: false
  446. IndentCaseLabels: false
  447. ColumnLimit: 0
  448. The result is:
  449. .. code-block:: c++
  450. void test()
  451. {
  452. switch (suffix)
  453. {
  454. case 0:
  455. case 1:
  456. do_something();
  457. break;
  458. case 2:
  459. do_something_else();
  460. break;
  461. default:
  462. break;
  463. }
  464. if (condition)
  465. do_somthing_completely_different();
  466. if (x == y)
  467. {
  468. q();
  469. }
  470. else if (x > y)
  471. {
  472. w();
  473. }
  474. else
  475. {
  476. r();
  477. }
  478. }