| 1 |
=========== |
| 2 |
ClangFormat |
| 3 |
=========== |
| 4 |
|
| 5 |
`ClangFormat` describes a set of tools that are built on top of |
| 6 |
:doc:`LibFormat`. It can support your workflow in a variety of ways including a |
| 7 |
standalone tool and editor integrations. |
| 8 |
|
| 9 |
|
| 10 |
Standalone Tool |
| 11 |
=============== |
| 12 |
|
| 13 |
:program:`clang-format` is located in `clang/tools/clang-format` and can be used |
| 14 |
to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code. |
| 15 |
|
| 16 |
.. START_FORMAT_HELP |
| 17 |
|
| 18 |
.. code-block:: console |
| 19 |
|
| 20 |
$ clang-format --help |
| 21 |
OVERVIEW: A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code. |
| 22 |
|
| 23 |
If no arguments are specified, it formats the code from standard input |
| 24 |
and writes the result to the standard output. |
| 25 |
If <file>s are given, it reformats the files. If -i is specified |
| 26 |
together with <file>s, the files are edited in-place. Otherwise, the |
| 27 |
result is written to the standard output. |
| 28 |
|
| 29 |
USAGE: clang-format [options] [@<file>] [<file> ...] |
| 30 |
|
| 31 |
OPTIONS: |
| 32 |
|
| 33 |
Clang-format options: |
| 34 |
|
| 35 |
--Werror - If set, changes formatting warnings to errors |
| 36 |
--Wno-error=<value> - If set, don't error out on the specified warning type. |
| 37 |
=unknown - If set, unknown format options are only warned about. |
| 38 |
This can be used to enable formatting, even if the |
| 39 |
configuration contains unknown (newer) options. |
| 40 |
Use with caution, as this might lead to dramatically |
| 41 |
differing format depending on an option being |
| 42 |
supported or not. |
| 43 |
--assume-filename=<string> - Set filename used to determine the language and to find |
| 44 |
.clang-format file. |
| 45 |
Only used when reading from stdin. |
| 46 |
If this is not passed, the .clang-format file is searched |
| 47 |
relative to the current working directory when reading stdin. |
| 48 |
Unrecognized filenames are treated as C++. |
| 49 |
supported: |
| 50 |
CSharp: .cs |
| 51 |
Java: .java |
| 52 |
JavaScript: .js .mjs .cjs .ts |
| 53 |
JSON: .json .ipynb |
| 54 |
Objective-C: .m .mm |
| 55 |
Proto: .proto .protodevel |
| 56 |
TableGen: .td |
| 57 |
TextProto: .txtpb .textpb .pb.txt .textproto .asciipb |
| 58 |
Verilog: .sv .svh .v .vh |
| 59 |
--cursor=<uint> - The position of the cursor when invoking |
| 60 |
clang-format from an editor integration |
| 61 |
--dry-run - If set, do not actually make the formatting changes |
| 62 |
--dump-config - Dump configuration options to stdout and exit. |
| 63 |
Can be used with -style option. |
| 64 |
--fail-on-incomplete-format - If set, fail with exit code 1 on incomplete format. |
| 65 |
--fallback-style=<string> - The name of the predefined style used as a |
| 66 |
fallback in case clang-format is invoked with |
| 67 |
-style=file, but can not find the .clang-format |
| 68 |
file to use. Defaults to 'LLVM'. |
| 69 |
Use -fallback-style=none to skip formatting. |
| 70 |
--ferror-limit=<uint> - Set the maximum number of clang-format errors to emit |
| 71 |
before stopping (0 = no limit). |
| 72 |
Used only with --dry-run or -n |
| 73 |
--files=<filename> - A file containing a list of files to process, one per line. |
| 74 |
-i - Inplace edit <file>s, if specified. |
| 75 |
--length=<uint> - Format a range of this length (in bytes). |
| 76 |
Multiple ranges can be formatted by specifying |
| 77 |
several -offset and -length pairs. |
| 78 |
When only a single -offset is specified without |
| 79 |
-length, clang-format will format up to the end |
| 80 |
of the file. |
| 81 |
Can only be used with one input file. |
| 82 |
--lines=<string> - <start line>:<end line> - format a range of |
| 83 |
lines (both 1-based). |
| 84 |
Multiple ranges can be formatted by specifying |
| 85 |
several -lines arguments. |
| 86 |
Can't be used with -offset and -length. |
| 87 |
Can only be used with one input file. |
| 88 |
-n - Alias for --dry-run |
| 89 |
--offset=<uint> - Format a range starting at this byte offset. |
| 90 |
Multiple ranges can be formatted by specifying |
| 91 |
several -offset and -length pairs. |
| 92 |
Can only be used with one input file. |
| 93 |
--output-replacements-xml - Output replacements as XML. |
| 94 |
--qualifier-alignment=<string> - If set, overrides the qualifier alignment style |
| 95 |
determined by the QualifierAlignment style flag |
| 96 |
--sort-includes - If set, overrides the include sorting behavior |
| 97 |
determined by the SortIncludes style flag |
| 98 |
--style=<string> - Set coding style. <string> can be: |
| 99 |
1. A preset: LLVM, GNU, Google, Chromium, Microsoft, |
| 100 |
Mozilla, WebKit. |
| 101 |
2. 'file' to load style configuration from a |
| 102 |
.clang-format file in one of the parent directories |
| 103 |
of the source file (for stdin, see --assume-filename). |
| 104 |
If no .clang-format file is found, falls back to |
| 105 |
--fallback-style. |
| 106 |
--style=file is the default. |
| 107 |
3. 'file:<format_file_path>' to explicitly specify |
| 108 |
the configuration file. |
| 109 |
4. "{key: value, ...}" to set specific parameters, e.g.: |
| 110 |
--style="{BasedOnStyle: llvm, IndentWidth: 8}" |
| 111 |
--verbose - If set, shows the list of processed files |
| 112 |
|
| 113 |
Generic Options: |
| 114 |
|
| 115 |
--help - Display available options (--help-hidden for more) |
| 116 |
--help-list - Display list of available options (--help-list-hidden for more) |
| 117 |
--version - Display the version of this program |
| 118 |
|
| 119 |
|
| 120 |
.. END_FORMAT_HELP |
| 121 |
|
| 122 |
When the desired code formatting style is different from the available options, |
| 123 |
the style can be customized using the ``-style="{key: value, ...}"`` option or |
| 124 |
by putting your style configuration in the ``.clang-format`` or ``_clang-format`` |
| 125 |
file in your project's directory and using ``clang-format -style=file``. |
| 126 |
|
| 127 |
An easy way to create the ``.clang-format`` file is: |
| 128 |
|
| 129 |
.. code-block:: console |
| 130 |
|
| 131 |
clang-format -style=llvm -dump-config > .clang-format |
| 132 |
|
| 133 |
Available style options are described in :doc:`ClangFormatStyleOptions`. |
| 134 |
|
| 135 |
.clang-format-ignore |
| 136 |
==================== |
| 137 |
|
| 138 |
You can create ``.clang-format-ignore`` files to make ``clang-format`` ignore |
| 139 |
certain files. A ``.clang-format-ignore`` file consists of patterns of file path |
| 140 |
names. It has the following format: |
| 141 |
|
| 142 |
* A blank line is skipped. |
| 143 |
* Leading and trailing spaces of a line are trimmed. |
| 144 |
* A line starting with a hash (``#``) is a comment. |
| 145 |
* A non-comment line is a single pattern. |
| 146 |
* The slash (``/``) is used as the directory separator. |
| 147 |
* A pattern is relative to the directory of the ``.clang-format-ignore`` file |
| 148 |
(or the root directory if the pattern starts with a slash). Patterns |
| 149 |
containing drive names (e.g. ``C:``) are not supported. |
| 150 |
* Patterns follow the rules specified in `POSIX 2.13.1, 2.13.2, and Rule 1 of |
| 151 |
2.13.3 <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ |
| 152 |
V3_chap02.html#tag_18_13>`_. |
| 153 |
* Bash globstar (``**``) is supported. |
| 154 |
* A pattern is negated if it starts with a bang (``!``). |
| 155 |
|
| 156 |
To match all files in a directory, use e.g. ``foo/bar/*``. To match all files in |
| 157 |
the directory of the ``.clang-format-ignore`` file, use ``*``. |
| 158 |
Multiple ``.clang-format-ignore`` files are supported similar to the |
| 159 |
``.clang-format`` files, with a lower directory level file voiding the higher |
| 160 |
level ones. |
| 161 |
|
| 162 |
Vim Integration |
| 163 |
=============== |
| 164 |
|
| 165 |
There is an integration for :program:`vim` which lets you run the |
| 166 |
:program:`clang-format` standalone tool on your current buffer, optionally |
| 167 |
selecting regions to reformat. The integration has the form of a `python`-file |
| 168 |
which can be found under `clang/tools/clang-format/clang-format.py`. |
| 169 |
|
| 170 |
This can be integrated by adding the following to your `.vimrc`: |
| 171 |
|
| 172 |
.. code-block:: vim |
| 173 |
|
| 174 |
if has('python') |
| 175 |
map <C-K> :pyf <path-to-this-file>/clang-format.py<cr> |
| 176 |
imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr> |
| 177 |
elseif has('python3') |
| 178 |
map <C-K> :py3f <path-to-this-file>/clang-format.py<cr> |
| 179 |
imap <C-K> <c-o>:py3f <path-to-this-file>/clang-format.py<cr> |
| 180 |
endif |
| 181 |
|
| 182 |
The first line enables :program:`clang-format` for NORMAL and VISUAL mode, the |
| 183 |
second line adds support for INSERT mode. Change "C-K" to another binding if |
| 184 |
you need :program:`clang-format` on a different key (C-K stands for Ctrl+k). |
| 185 |
|
| 186 |
With this integration you can press the bound key and clang-format will |
| 187 |
format the current line in NORMAL and INSERT mode or the selected region in |
| 188 |
VISUAL mode. The line or region is extended to the next bigger syntactic |
| 189 |
entity. |
| 190 |
|
| 191 |
It operates on the current, potentially unsaved buffer and does not create |
| 192 |
or save any files. To revert a formatting, just undo. |
| 193 |
|
| 194 |
An alternative option is to format changes when saving a file and thus to |
| 195 |
have a zero-effort integration into the coding workflow. To do this, add this to |
| 196 |
your `.vimrc`: |
| 197 |
|
| 198 |
.. code-block:: vim |
| 199 |
|
| 200 |
function! Formatonsave() |
| 201 |
let l:formatdiff = 1 |
| 202 |
pyf <path-to-this-file>/clang-format.py |
| 203 |
endfunction |
| 204 |
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave() |
| 205 |
|
| 206 |
|
| 207 |
Emacs Integration |
| 208 |
================= |
| 209 |
|
| 210 |
Similar to the integration for :program:`vim`, there is an integration for |
| 211 |
:program:`emacs`. It can be found at `clang/tools/clang-format/clang-format.el` |
| 212 |
and used by adding this to your `.emacs`: |
| 213 |
|
| 214 |
.. code-block:: common-lisp |
| 215 |
|
| 216 |
(load "<path-to-clang>/tools/clang-format/clang-format.el") |
| 217 |
(global-set-key [C-M-tab] 'clang-format-region) |
| 218 |
|
| 219 |
This binds the function `clang-format-region` to C-M-tab, which then formats the |
| 220 |
current line or selected region. |
| 221 |
|
| 222 |
|
| 223 |
BBEdit Integration |
| 224 |
================== |
| 225 |
|
| 226 |
:program:`clang-format` cannot be used as a text filter with BBEdit, but works |
| 227 |
well via a script. The AppleScript to do this integration can be found at |
| 228 |
`clang/tools/clang-format/clang-format-bbedit.applescript`; place a copy in |
| 229 |
`~/Library/Application Support/BBEdit/Scripts`, and edit the path within it to |
| 230 |
point to your local copy of :program:`clang-format`. |
| 231 |
|
| 232 |
With this integration you can select the script from the Script menu and |
| 233 |
:program:`clang-format` will format the selection. Note that you can rename the |
| 234 |
menu item by renaming the script, and can assign the menu item a keyboard |
| 235 |
shortcut in the BBEdit preferences, under Menus & Shortcuts. |
| 236 |
|
| 237 |
|
| 238 |
CLion Integration |
| 239 |
================= |
| 240 |
|
| 241 |
:program:`clang-format` is integrated into `CLion <https://www.jetbrains |
| 242 |
.com/clion/>`_ as an alternative code formatter. CLion turns it on |
| 243 |
automatically when there is a ``.clang-format`` file under the project root. |
| 244 |
Code style rules are applied as you type, including indentation, |
| 245 |
auto-completion, code generation, and refactorings. |
| 246 |
|
| 247 |
:program:`clang-format` can also be enabled without a ``.clang-format`` file. |
| 248 |
In this case, CLion prompts you to create one based on the current IDE settings |
| 249 |
or the default LLVM style. |
| 250 |
|
| 251 |
|
| 252 |
Visual Studio Integration |
| 253 |
========================= |
| 254 |
|
| 255 |
Download the latest Visual Studio extension from the `alpha build site |
| 256 |
<https://llvm.org/builds/>`_. The default key-binding is Ctrl-R,Ctrl-F. |
| 257 |
|
| 258 |
|
| 259 |
Visual Studio Code Integration |
| 260 |
============================== |
| 261 |
|
| 262 |
Get the latest Visual Studio Code extension from the `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=xaver.clang-format>`_. The default key-binding is Alt-Shift-F. |
| 263 |
|
| 264 |
Git integration |
| 265 |
=============== |
| 266 |
|
| 267 |
The script `clang/tools/clang-format/git-clang-format` can be used to |
| 268 |
format just the lines touched in git commits: |
| 269 |
|
| 270 |
.. code-block:: console |
| 271 |
|
| 272 |
% git clang-format -h |
| 273 |
usage: git clang-format [OPTIONS] [<commit>] [<commit>|--staged] [--] [<file>...] |
| 274 |
|
| 275 |
If zero or one commits are given, run clang-format on all lines that differ |
| 276 |
between the working directory and <commit>, which defaults to HEAD. Changes are |
| 277 |
only applied to the working directory, or in the stage/index. |
| 278 |
|
| 279 |
Examples: |
| 280 |
To format staged changes, i.e everything that's been `git add`ed: |
| 281 |
git clang-format |
| 282 |
|
| 283 |
To also format everything touched in the most recent commit: |
| 284 |
git clang-format HEAD~1 |
| 285 |
|
| 286 |
If you're on a branch off main, to format everything touched on your branch: |
| 287 |
git clang-format main |
| 288 |
|
| 289 |
If two commits are given (requires --diff), run clang-format on all lines in the |
| 290 |
second <commit> that differ from the first <commit>. |
| 291 |
|
| 292 |
The following git-config settings set the default of the corresponding option: |
| 293 |
clangFormat.binary |
| 294 |
clangFormat.commit |
| 295 |
clangFormat.extensions |
| 296 |
clangFormat.style |
| 297 |
|
| 298 |
positional arguments: |
| 299 |
<commit> revision from which to compute the diff |
| 300 |
<file>... if specified, only consider differences in these files |
| 301 |
|
| 302 |
optional arguments: |
| 303 |
-h, --help show this help message and exit |
| 304 |
--binary BINARY path to clang-format |
| 305 |
--commit COMMIT default commit to use if none is specified |
| 306 |
--diff print a diff instead of applying the changes |
| 307 |
--diffstat print a diffstat instead of applying the changes |
| 308 |
--extensions EXTENSIONS |
| 309 |
comma-separated list of file extensions to format, excluding the period and case-insensitive |
| 310 |
-f, --force allow changes to unstaged files |
| 311 |
-p, --patch select hunks interactively |
| 312 |
-q, --quiet print less information |
| 313 |
--staged, --cached format lines in the stage instead of the working dir |
| 314 |
--style STYLE passed to clang-format |
| 315 |
-v, --verbose print extra information |
| 316 |
|
| 317 |
|
| 318 |
Script for patch reformatting |
| 319 |
============================= |
| 320 |
|
| 321 |
The python script `clang/tools/clang-format/clang-format-diff.py` parses the |
| 322 |
output of a unified diff and reformats all contained lines with |
| 323 |
:program:`clang-format`. |
| 324 |
|
| 325 |
.. code-block:: console |
| 326 |
|
| 327 |
usage: clang-format-diff.py [-h] [-i] [-p NUM] [-regex PATTERN] [-iregex PATTERN] [-sort-includes] [-v] [-style STYLE] |
| 328 |
[-fallback-style FALLBACK_STYLE] [-binary BINARY] |
| 329 |
|
| 330 |
This script reads input from a unified diff and reformats all the changed |
| 331 |
lines. This is useful to reformat all the lines touched by a specific patch. |
| 332 |
Example usage for git/svn users: |
| 333 |
|
| 334 |
git diff -U0 --no-color --relative HEAD^ | clang-format-diff.py -p1 -i |
| 335 |
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i |
| 336 |
|
| 337 |
It should be noted that the filename contained in the diff is used unmodified |
| 338 |
to determine the source file to update. Users calling this script directly |
| 339 |
should be careful to ensure that the path in the diff is correct relative to the |
| 340 |
current working directory. |
| 341 |
|
| 342 |
optional arguments: |
| 343 |
-h, --help show this help message and exit |
| 344 |
-i apply edits to files instead of displaying a diff |
| 345 |
-p NUM strip the smallest prefix containing P slashes |
| 346 |
-regex PATTERN custom pattern selecting file paths to reformat (case sensitive, overrides -iregex) |
| 347 |
-iregex PATTERN custom pattern selecting file paths to reformat (case insensitive, overridden by -regex) |
| 348 |
-sort-includes let clang-format sort include blocks |
| 349 |
-v, --verbose be more verbose, ineffective without -i |
| 350 |
-style STYLE formatting style to apply (LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit) |
| 351 |
-fallback-style FALLBACK_STYLE |
| 352 |
The name of the predefined style used as a fallback in case clang-format is invoked with-style=file, but can not |
| 353 |
find the .clang-formatfile to use. |
| 354 |
-binary BINARY location of binary to use for clang-format |
| 355 |
|
| 356 |
To reformat all the lines in the latest Mercurial/:program:`hg` commit, do: |
| 357 |
|
| 358 |
.. code-block:: console |
| 359 |
|
| 360 |
hg diff -U0 --color=never | clang-format-diff.py -i -p1 |
| 361 |
|
| 362 |
The option `-U0` will create a diff without context lines (the script would format |
| 363 |
those as well). |
| 364 |
|
| 365 |
These commands use the file paths shown in the diff output |
| 366 |
so they will only work from the root of the repository. |