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