ClangFormat.rst revision 1.1.1.3
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.. code-block:: console
17
18  $ clang-format -help
19  OVERVIEW: A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.
20
21  If no arguments are specified, it formats the code from standard input
22  and writes the result to the standard output.
23  If <file>s are given, it reformats the files. If -i is specified
24  together with <file>s, the files are edited in-place. Otherwise, the
25  result is written to the standard output.
26
27  USAGE: clang-format [options] [<file> ...]
28
29  OPTIONS:
30
31  Clang-format options:
32
33    --Werror                   - If set, changes formatting warnings to errors
34    --Wno-error=<value>        - If set don't error out on the specified warning type.
35      =unknown                 -   If set, unknown format options are only warned about.
36                                   This can be used to enable formatting, even if the
37                                   configuration contains unknown (newer) options.
38                                   Use with caution, as this might lead to dramatically
39                                   differing format depending on an option being
40                                   supported or not.
41    --assume-filename=<string> - Override filename used to determine the language.
42                                 When reading from stdin, clang-format assumes this
43                                 filename to determine the language.
44    --cursor=<uint>            - The position of the cursor when invoking
45                                 clang-format from an editor integration
46    --dry-run                  - If set, do not actually make the formatting changes
47    --dump-config              - Dump configuration options to stdout and exit.
48                                 Can be used with -style option.
49    --fallback-style=<string>  - The name of the predefined style used as a
50                                 fallback in case clang-format is invoked with
51                                 -style=file, but can not find the .clang-format
52                                 file to use.
53                                 Use -fallback-style=none to skip formatting.
54    --ferror-limit=<uint>      - Set the maximum number of clang-format errors to
55                                 emit before stopping (0 = no limit). Used only
56                                 with --dry-run or -n
57    -i                         - Inplace edit <file>s, if specified.
58    --length=<uint>            - Format a range of this length (in bytes).
59                                 Multiple ranges can be formatted by specifying
60                                 several -offset and -length pairs.
61                                 When only a single -offset is specified without
62                                 -length, clang-format will format up to the end
63                                 of the file.
64                                 Can only be used with one input file.
65    --lines=<string>           - <start line>:<end line> - format a range of
66                                 lines (both 1-based).
67                                 Multiple ranges can be formatted by specifying
68                                 several -lines arguments.
69                                 Can't be used with -offset and -length.
70                                 Can only be used with one input file.
71    -n                         - Alias for --dry-run
72    --offset=<uint>            - Format a range starting at this byte offset.
73                                 Multiple ranges can be formatted by specifying
74                                 several -offset and -length pairs.
75                                 Can only be used with one input file.
76    --output-replacements-xml  - Output replacements as XML.
77    --sort-includes            - If set, overrides the include sorting behavior
78                                 determined by the SortIncludes style flag
79    --style=<string>           - Coding style, currently supports:
80                                   LLVM, Google, Chromium, Mozilla, WebKit.
81                                 Use -style=file to load style configuration from
82                                 .clang-format file located in one of the parent
83                                 directories of the source file (or current
84                                 directory for stdin).
85                                 Use -style="{key: value, ...}" to set specific
86                                 parameters, e.g.:
87                                   -style="{BasedOnStyle: llvm, IndentWidth: 8}"
88    --verbose                  - If set, shows the list of processed files
89
90  Generic Options:
91
92    --help                     - Display available options (--help-hidden for more)
93    --help-list                - Display list of available options (--help-list-hidden for more)
94    --version                  - Display the version of this program
95
96
97When the desired code formatting style is different from the available options,
98the style can be customized using the ``-style="{key: value, ...}"`` option or
99by putting your style configuration in the ``.clang-format`` or ``_clang-format``
100file in your project's directory and using ``clang-format -style=file``.
101
102An easy way to create the ``.clang-format`` file is:
103
104.. code-block:: console
105
106  clang-format -style=llvm -dump-config > .clang-format
107
108Available style options are described in :doc:`ClangFormatStyleOptions`.
109
110
111Vim Integration
112===============
113
114There is an integration for :program:`vim` which lets you run the
115:program:`clang-format` standalone tool on your current buffer, optionally
116selecting regions to reformat. The integration has the form of a `python`-file
117which can be found under `clang/tools/clang-format/clang-format.py`.
118
119This can be integrated by adding the following to your `.vimrc`:
120
121.. code-block:: vim
122
123  map <C-K> :pyf <path-to-this-file>/clang-format.py<cr>
124  imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
125
126The first line enables :program:`clang-format` for NORMAL and VISUAL mode, the
127second line adds support for INSERT mode. Change "C-K" to another binding if
128you need :program:`clang-format` on a different key (C-K stands for Ctrl+k).
129
130With this integration you can press the bound key and clang-format will
131format the current line in NORMAL and INSERT mode or the selected region in
132VISUAL mode. The line or region is extended to the next bigger syntactic
133entity.
134
135It operates on the current, potentially unsaved buffer and does not create
136or save any files. To revert a formatting, just undo.
137
138An alternative option is to format changes when saving a file and thus to
139have a zero-effort integration into the coding workflow. To do this, add this to
140your `.vimrc`:
141
142.. code-block:: vim
143
144  function! Formatonsave()
145    let l:formatdiff = 1
146    pyf ~/llvm/tools/clang/tools/clang-format/clang-format.py
147  endfunction
148  autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
149
150
151Emacs Integration
152=================
153
154Similar to the integration for :program:`vim`, there is an integration for
155:program:`emacs`. It can be found at `clang/tools/clang-format/clang-format.el`
156and used by adding this to your `.emacs`:
157
158.. code-block:: common-lisp
159
160  (load "<path-to-clang>/tools/clang-format/clang-format.el")
161  (global-set-key [C-M-tab] 'clang-format-region)
162
163This binds the function `clang-format-region` to C-M-tab, which then formats the
164current line or selected region.
165
166
167BBEdit Integration
168==================
169
170:program:`clang-format` cannot be used as a text filter with BBEdit, but works
171well via a script. The AppleScript to do this integration can be found at
172`clang/tools/clang-format/clang-format-bbedit.applescript`; place a copy in
173`~/Library/Application Support/BBEdit/Scripts`, and edit the path within it to
174point to your local copy of :program:`clang-format`.
175
176With this integration you can select the script from the Script menu and
177:program:`clang-format` will format the selection. Note that you can rename the
178menu item by renaming the script, and can assign the menu item a keyboard
179shortcut in the BBEdit preferences, under Menus & Shortcuts.
180
181
182CLion Integration
183=================
184
185:program:`clang-format` is integrated into `CLion <https://www.jetbrains
186.com/clion/>`_ as an alternative code formatter. CLion turns it on
187automatically when there is a ``.clang-format`` file under the project root.
188Code style rules are applied as you type, including indentation,
189auto-completion, code generation, and refactorings.
190
191:program:`clang-format` can also be enabled without a ``.clang-format`` file.
192In this case, CLion prompts you to create one based on the current IDE settings
193or the default LLVM style.
194
195
196Visual Studio Integration
197=========================
198
199Download the latest Visual Studio extension from the `alpha build site
200<https://llvm.org/builds/>`_. The default key-binding is Ctrl-R,Ctrl-F.
201
202
203Visual Studio Code Integration
204==============================
205
206Get 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.
207
208
209Script for patch reformatting
210=============================
211
212The python script `clang/tools/clang-format/clang-format-diff.py` parses the
213output of a unified diff and reformats all contained lines with
214:program:`clang-format`.
215
216.. code-block:: console
217
218  usage: clang-format-diff.py [-h] [-i] [-p NUM] [-regex PATTERN] [-style STYLE]
219
220  Reformat changed lines in diff. Without -i option just output the diff that
221  would be introduced.
222
223  optional arguments:
224    -h, --help      show this help message and exit
225    -i              apply edits to files instead of displaying a diff
226    -p NUM          strip the smallest prefix containing P slashes
227    -regex PATTERN  custom pattern selecting file paths to reformat
228    -style STYLE    formatting style to apply (LLVM, Google, Chromium, Mozilla,
229                    WebKit)
230
231So to reformat all the lines in the latest :program:`git` commit, just do:
232
233.. code-block:: console
234
235  git diff -U0 --no-color HEAD^ | clang-format-diff.py -i -p1
236
237With Mercurial/:program:`hg`:
238
239.. code-block:: console
240
241  hg diff -U0 --color=never | clang-format-diff.py -i -p1
242
243In an SVN client, you can do:
244
245.. code-block:: console
246
247  svn diff --diff-cmd=diff -x -U0 | clang-format-diff.py -i
248
249The option `-U0` will create a diff without context lines (the script would format
250those as well).
251
252These commands use the file paths shown in the diff output
253so they will only work from the root of the repository.
254
255Current State of Clang Format for LLVM
256======================================
257
258The following table :doc:`ClangFormattedStatus` shows the current status of clang-formatting for the entire LLVM source tree.
259