1===========
2ClangFormat
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
7standalone tool and editor integrations.
8
9
10Standalone Tool
11===============
12
13:program:`clang-format` is located in `clang/tools/clang-format` and can be used
14to 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> ...]
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: .mjs .js .ts
53                                       Json: .json
54                                       Objective-C: .m .mm
55                                       Proto: .proto .protodevel
56                                       TableGen: .td
57                                       TextProto: .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    --fallback-style=<string>      - The name of the predefined style used as a
65                                     fallback in case clang-format is invoked with
66                                     -style=file, but can not find the .clang-format
67                                     file to use. Defaults to 'LLVM'.
68                                     Use -fallback-style=none to skip formatting.
69    --ferror-limit=<uint>          - Set the maximum number of clang-format errors to emit
70                                     before stopping (0 = no limit).
71                                     Used only with --dry-run or -n
72    --files=<string>               - Provide a list of files to run clang-format
73    -i                             - Inplace edit <file>s, if specified.
74    --length=<uint>                - Format a range of this length (in bytes).
75                                     Multiple ranges can be formatted by specifying
76                                     several -offset and -length pairs.
77                                     When only a single -offset is specified without
78                                     -length, clang-format will format up to the end
79                                     of the file.
80                                     Can only be used with one input file.
81    --lines=<string>               - <start line>:<end line> - format a range of
82                                     lines (both 1-based).
83                                     Multiple ranges can be formatted by specifying
84                                     several -lines arguments.
85                                     Can't be used with -offset and -length.
86                                     Can only be used with one input file.
87    -n                             - Alias for --dry-run
88    --offset=<uint>                - Format a range starting at this byte offset.
89                                     Multiple ranges can be formatted by specifying
90                                     several -offset and -length pairs.
91                                     Can only be used with one input file.
92    --output-replacements-xml      - Output replacements as XML.
93    --qualifier-alignment=<string> - If set, overrides the qualifier alignment style
94                                     determined by the QualifierAlignment style flag
95    --sort-includes                - If set, overrides the include sorting behavior
96                                     determined by the SortIncludes style flag
97    --style=<string>               - Set coding style. <string> can be:
98                                     1. A preset: LLVM, GNU, Google, Chromium, Microsoft,
99                                        Mozilla, WebKit.
100                                     2. 'file' to load style configuration from a
101                                        .clang-format file in one of the parent directories
102                                        of the source file (for stdin, see --assume-filename).
103                                        If no .clang-format file is found, falls back to
104                                        --fallback-style.
105                                        --style=file is the default.
106                                     3. 'file:<format_file_path>' to explicitly specify
107                                        the configuration file.
108                                     4. "{key: value, ...}" to set specific parameters, e.g.:
109                                        --style="{BasedOnStyle: llvm, IndentWidth: 8}"
110    --verbose                      - If set, shows the list of processed files
111
112  Generic Options:
113
114    --help                         - Display available options (--help-hidden for more)
115    --help-list                    - Display list of available options (--help-list-hidden for more)
116    --version                      - Display the version of this program
117
118
119.. END_FORMAT_HELP
120
121When the desired code formatting style is different from the available options,
122the style can be customized using the ``-style="{key: value, ...}"`` option or
123by putting your style configuration in the ``.clang-format`` or ``_clang-format``
124file in your project's directory and using ``clang-format -style=file``.
125
126An easy way to create the ``.clang-format`` file is:
127
128.. code-block:: console
129
130  clang-format -style=llvm -dump-config > .clang-format
131
132Available style options are described in :doc:`ClangFormatStyleOptions`.
133
134
135Vim Integration
136===============
137
138There is an integration for :program:`vim` which lets you run the
139:program:`clang-format` standalone tool on your current buffer, optionally
140selecting regions to reformat. The integration has the form of a `python`-file
141which can be found under `clang/tools/clang-format/clang-format.py`.
142
143This can be integrated by adding the following to your `.vimrc`:
144
145.. code-block:: vim
146
147  map <C-K> :pyf <path-to-this-file>/clang-format.py<cr>
148  imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
149
150The first line enables :program:`clang-format` for NORMAL and VISUAL mode, the
151second line adds support for INSERT mode. Change "C-K" to another binding if
152you need :program:`clang-format` on a different key (C-K stands for Ctrl+k).
153
154With this integration you can press the bound key and clang-format will
155format the current line in NORMAL and INSERT mode or the selected region in
156VISUAL mode. The line or region is extended to the next bigger syntactic
157entity.
158
159It operates on the current, potentially unsaved buffer and does not create
160or save any files. To revert a formatting, just undo.
161
162An alternative option is to format changes when saving a file and thus to
163have a zero-effort integration into the coding workflow. To do this, add this to
164your `.vimrc`:
165
166.. code-block:: vim
167
168  function! Formatonsave()
169    let l:formatdiff = 1
170    pyf ~/llvm/tools/clang/tools/clang-format/clang-format.py
171  endfunction
172  autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
173
174
175Emacs Integration
176=================
177
178Similar to the integration for :program:`vim`, there is an integration for
179:program:`emacs`. It can be found at `clang/tools/clang-format/clang-format.el`
180and used by adding this to your `.emacs`:
181
182.. code-block:: common-lisp
183
184  (load "<path-to-clang>/tools/clang-format/clang-format.el")
185  (global-set-key [C-M-tab] 'clang-format-region)
186
187This binds the function `clang-format-region` to C-M-tab, which then formats the
188current line or selected region.
189
190
191BBEdit Integration
192==================
193
194:program:`clang-format` cannot be used as a text filter with BBEdit, but works
195well via a script. The AppleScript to do this integration can be found at
196`clang/tools/clang-format/clang-format-bbedit.applescript`; place a copy in
197`~/Library/Application Support/BBEdit/Scripts`, and edit the path within it to
198point to your local copy of :program:`clang-format`.
199
200With this integration you can select the script from the Script menu and
201:program:`clang-format` will format the selection. Note that you can rename the
202menu item by renaming the script, and can assign the menu item a keyboard
203shortcut in the BBEdit preferences, under Menus & Shortcuts.
204
205
206CLion Integration
207=================
208
209:program:`clang-format` is integrated into `CLion <https://www.jetbrains
210.com/clion/>`_ as an alternative code formatter. CLion turns it on
211automatically when there is a ``.clang-format`` file under the project root.
212Code style rules are applied as you type, including indentation,
213auto-completion, code generation, and refactorings.
214
215:program:`clang-format` can also be enabled without a ``.clang-format`` file.
216In this case, CLion prompts you to create one based on the current IDE settings
217or the default LLVM style.
218
219
220Visual Studio Integration
221=========================
222
223Download the latest Visual Studio extension from the `alpha build site
224<https://llvm.org/builds/>`_. The default key-binding is Ctrl-R,Ctrl-F.
225
226
227Visual Studio Code Integration
228==============================
229
230Get 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.
231
232
233Script for patch reformatting
234=============================
235
236The python script `clang/tools/clang-format/clang-format-diff.py` parses the
237output of a unified diff and reformats all contained lines with
238:program:`clang-format`.
239
240.. code-block:: console
241
242  usage: clang-format-diff.py [-h] [-i] [-p NUM] [-regex PATTERN] [-iregex PATTERN] [-sort-includes] [-v] [-style STYLE]
243                              [-fallback-style FALLBACK_STYLE] [-binary BINARY]
244
245  This script reads input from a unified diff and reformats all the changed
246  lines. This is useful to reformat all the lines touched by a specific patch.
247  Example usage for git/svn users:
248
249    git diff -U0 --no-color --relative HEAD^ | clang-format-diff.py -p1 -i
250    svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
251
252  It should be noted that the filename contained in the diff is used unmodified
253  to determine the source file to update. Users calling this script directly
254  should be careful to ensure that the path in the diff is correct relative to the
255  current working directory.
256
257  optional arguments:
258    -h, --help            show this help message and exit
259    -i                    apply edits to files instead of displaying a diff
260    -p NUM                strip the smallest prefix containing P slashes
261    -regex PATTERN        custom pattern selecting file paths to reformat (case sensitive, overrides -iregex)
262    -iregex PATTERN       custom pattern selecting file paths to reformat (case insensitive, overridden by -regex)
263    -sort-includes        let clang-format sort include blocks
264    -v, --verbose         be more verbose, ineffective without -i
265    -style STYLE          formatting style to apply (LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit)
266    -fallback-style FALLBACK_STYLE
267                          The name of the predefined style used as afallback in case clang-format is invoked with-style=file, but can not
268                          find the .clang-formatfile to use.
269    -binary BINARY        location of binary to use for clang-format
270
271To reformat all the lines in the latest Mercurial/:program:`hg` commit, do:
272
273.. code-block:: console
274
275  hg diff -U0 --color=never | clang-format-diff.py -i -p1
276
277The option `-U0` will create a diff without context lines (the script would format
278those as well).
279
280These commands use the file paths shown in the diff output
281so they will only work from the root of the repository.
282
283Current State of Clang Format for LLVM
284======================================
285
286The following table :doc:`ClangFormattedStatus` shows the current status of clang-formatting for the entire LLVM source tree.
287