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