]> git.madduck.net Git - etc/vim.git/blob - docs/usage_and_configuration/the_basics.md

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Use aware datetimes to represent UTC (#3728)
[etc/vim.git] / docs / usage_and_configuration / the_basics.md
1 # The basics
2
3 Foundational knowledge on using and configuring Black.
4
5 _Black_ is a well-behaved Unix-style command-line tool:
6
7 - it does nothing if it finds no sources to format;
8 - it will read from standard input and write to standard output if `-` is used as the
9   filename;
10 - it only outputs messages to users on standard error;
11 - exits with code 0 unless an internal error occurred or a CLI option prompted it.
12
13 ## Usage
14
15 To get started right away with sensible defaults:
16
17 ```sh
18 black {source_file_or_directory}
19 ```
20
21 You can run _Black_ as a package if running it as a script doesn't work:
22
23 ```sh
24 python -m black {source_file_or_directory}
25 ```
26
27 ### Command line options
28
29 The CLI options of _Black_ can be displayed by running `black --help`. All options are
30 also covered in more detail below.
31
32 While _Black_ has quite a few knobs these days, it is still opinionated so style options
33 are deliberately limited and rarely added.
34
35 Note that all command-line options listed above can also be configured using a
36 `pyproject.toml` file (more on that below).
37
38 #### `-c`, `--code`
39
40 Format the code passed in as a string.
41
42 ```console
43 $ black --code "print ( 'hello, world' )"
44 print("hello, world")
45 ```
46
47 #### `-l`, `--line-length`
48
49 How many characters per line to allow. The default is 88.
50
51 See also [the style documentation](labels/line-length).
52
53 #### `-t`, `--target-version`
54
55 Python versions that should be supported by Black's output. You should include all
56 versions that your code supports. If you support Python 3.7 through 3.10, you should
57 write:
58
59 ```console
60 $ black -t py37 -t py38 -t py39 -t py310
61 ```
62
63 In a [configuration file](#configuration-via-a-file), you can write:
64
65 ```toml
66 target-versions = ["py37", "py38", "py39", "py310"]
67 ```
68
69 _Black_ uses this option to decide what grammar to use to parse your code. In addition,
70 it may use it to decide what style to use. For example, support for a trailing comma
71 after `*args` in a function call was added in Python 3.5, so _Black_ will add this comma
72 only if the target versions are all Python 3.5 or higher:
73
74 ```console
75 $ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
76 f(
77     a,
78     *args,
79 )
80 $ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
81 f(
82     a,
83     *args
84 )
85 $ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
86 f(
87     a,
88     *args
89 )
90 ```
91
92 #### `--pyi`
93
94 Format all input files like typing stubs regardless of file extension. This is useful
95 when piping source on standard input.
96
97 #### `--ipynb`
98
99 Format all input files like Jupyter Notebooks regardless of file extension. This is
100 useful when piping source on standard input.
101
102 #### `--python-cell-magics`
103
104 When processing Jupyter Notebooks, add the given magic to the list of known python-
105 magics. Useful for formatting cells with custom python magics.
106
107 #### `-S, --skip-string-normalization`
108
109 By default, _Black_ uses double quotes for all strings and normalizes string prefixes,
110 as described in [the style documentation](labels/strings). If this option is given,
111 strings are left unchanged instead.
112
113 #### `-C, --skip-magic-trailing-comma`
114
115 By default, _Black_ uses existing trailing commas as an indication that short lines
116 should be left separate, as described in
117 [the style documentation](labels/magic-trailing-comma). If this option is given, the
118 magic trailing comma is ignored.
119
120 #### `--preview`
121
122 Enable potentially disruptive style changes that may be added to Black's main
123 functionality in the next major release. Read more about
124 [our preview style](labels/preview-style).
125
126 (labels/exit-code)=
127
128 #### `--check`
129
130 Passing `--check` will make _Black_ exit with:
131
132 - code 0 if nothing would change;
133 - code 1 if some files would be reformatted; or
134 - code 123 if there was an internal error
135
136 ```console
137 $ black test.py --check
138 All done! ✨ 🍰 ✨
139 1 file would be left unchanged.
140 $ echo $?
141 0
142
143 $ black test.py --check
144 would reformat test.py
145 Oh no! 💥 💔 💥
146 1 file would be reformatted.
147 $ echo $?
148 1
149
150 $ black test.py --check
151 error: cannot format test.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_kjdr1oog.log
152 Oh no! 💥 💔 💥
153 1 file would fail to reformat.
154 $ echo $?
155 123
156 ```
157
158 #### `--diff`
159
160 Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_
161 would've made. They are printed to stdout so capturing them is simple.
162
163 If you'd like colored diffs, you can enable them with `--color`.
164
165 ```console
166 $ black test.py --diff
167 --- test.py     2021-03-08 22:23:40.848954+00:00
168 +++ test.py     2021-03-08 22:23:47.126319+00:00
169 @@ -1 +1 @@
170 -print ( 'hello, world' )
171 +print("hello, world")
172 would reformat test.py
173 All done! ✨ 🍰 ✨
174 1 file would be reformatted.
175 ```
176
177 #### `--color` / `--no-color`
178
179 Show (or do not show) colored diff. Only applies when `--diff` is given.
180
181 #### `--fast` / `--safe`
182
183 By default, _Black_ performs [an AST safety check](labels/ast-changes) after formatting
184 your code. The `--fast` flag turns off this check and the `--safe` flag explicitly
185 enables it.
186
187 #### `--required-version`
188
189 Require a specific version of _Black_ to be running. This is useful for ensuring that
190 all contributors to your project are using the same version, because different versions
191 of _Black_ may format code a little differently. This option can be set in a
192 configuration file for consistent results across environments.
193
194 ```console
195 $ black --version
196 black, 23.3.0 (compiled: yes)
197 $ black --required-version 23.3.0 -c "format = 'this'"
198 format = "this"
199 $ black --required-version 31.5b2 -c "still = 'beta?!'"
200 Oh no! 💥 💔 💥 The required version does not match the running version!
201 ```
202
203 You can also pass just the major version:
204
205 ```console
206 $ black --required-version 22 -c "format = 'this'"
207 format = "this"
208 $ black --required-version 31 -c "still = 'beta?!'"
209 Oh no! 💥 💔 💥 The required version does not match the running version!
210 ```
211
212 Because of our [stability policy](../the_black_code_style/index.md), this will guarantee
213 stable formatting, but still allow you to take advantage of improvements that do not
214 affect formatting.
215
216 #### `--include`
217
218 A regular expression that matches files and directories that should be included on
219 recursive searches. An empty value means all files are included regardless of the name.
220 Use forward slashes for directories on all platforms (Windows, too). Exclusions are
221 calculated first, inclusions later.
222
223 #### `--exclude`
224
225 A regular expression that matches files and directories that should be excluded on
226 recursive searches. An empty value means no paths are excluded. Use forward slashes for
227 directories on all platforms (Windows, too). Exclusions are calculated first, inclusions
228 later.
229
230 #### `--extend-exclude`
231
232 Like `--exclude`, but adds additional files and directories on top of the excluded ones.
233 Useful if you simply want to add to the default.
234
235 #### `--force-exclude`
236
237 Like `--exclude`, but files and directories matching this regex will be excluded even
238 when they are passed explicitly as arguments. This is useful when invoking _Black_
239 programmatically on changed files, such as in a pre-commit hook or editor plugin.
240
241 #### `--stdin-filename`
242
243 The name of the file when passing it through stdin. Useful to make sure Black will
244 respect the `--force-exclude` option on some editors that rely on using stdin.
245
246 #### `-W`, `--workers`
247
248 When _Black_ formats multiple files, it may use a process pool to speed up formatting.
249 This option controls the number of parallel workers.
250
251 #### `-q`, `--quiet`
252
253 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critical output.
254 Error messages will still be emitted (which can silenced by `2>/dev/null`).
255
256 ```console
257 $ black src/ -q
258 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
259 ```
260
261 #### `-v`, `--verbose`
262
263 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
264 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
265 configuration file, a blue message detailing which one it is using will be emitted.
266
267 ```console
268 $ black src/ -v
269 Using configuration from /tmp/pyproject.toml.
270 src/blib2to3 ignored: matches the --extend-exclude regular expression
271 src/_black_version.py wasn't modified on disk since last run.
272 src/black/__main__.py wasn't modified on disk since last run.
273 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
274 reformatted src/black_primer/lib.py
275 reformatted src/blackd/__init__.py
276 reformatted src/black/__init__.py
277 Oh no! 💥 💔 💥
278 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
279 ```
280
281 #### `--version`
282
283 You can check the version of _Black_ you have installed using the `--version` flag.
284
285 ```console
286 $ black --version
287 black, 23.3.0
288 ```
289
290 #### `--config`
291
292 Read configuration options from a configuration file. See
293 [below](#configuration-via-a-file) for more details on the configuration file.
294
295 #### `-h`, `--help`
296
297 Show available command-line options and exit.
298
299 ### Code input alternatives
300
301 _Black_ supports formatting code via stdin, with the result being printed to stdout.
302 Just let _Black_ know with `-` as the path.
303
304 ```console
305 $ echo "print ( 'hello, world' )" | black -
306 print("hello, world")
307 reformatted -
308 All done! ✨ 🍰 ✨
309 1 file reformatted.
310 ```
311
312 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
313 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
314 option on some editors that rely on using stdin.
315
316 You can also pass code as a string using the `-c` / `--code` option.
317
318 ### Writeback and reporting
319
320 By default _Black_ reformats the files given and/or found in place. Sometimes you need
321 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
322
323 There's two variations to this mode that are independently enabled by their respective
324 flags:
325
326 - `--check` (exit with code 1 if any file would be reformatted)
327 - `--diff` (print a diff instead of reformatting files)
328
329 Both variations can be enabled at once.
330
331 ### Output verbosity
332
333 _Black_ in general tries to produce the right amount of output, balancing between
334 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
335 plus a short summary.
336
337 ```console
338 $ black src/
339 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
340 reformatted src/black_primer/lib.py
341 reformatted src/blackd/__init__.py
342 reformatted src/black/__init__.py
343 Oh no! 💥 💔 💥
344 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
345 ```
346
347 The `--quiet` and `--verbose` flags control output verbosity.
348
349 ## Configuration via a file
350
351 _Black_ is able to read project-specific default values for its command line options
352 from a `pyproject.toml` file. This is especially useful for specifying custom
353 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
354 project.
355
356 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
357 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
358 code in compliance with many other _Black_ formatted projects.
359
360 ### What on Earth is a `pyproject.toml` file?
361
362 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
363 configuration file to store build system requirements for Python projects. With the help
364 of tools like [Poetry](https://python-poetry.org/),
365 [Flit](https://flit.readthedocs.io/en/latest/), or
366 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
367 `setup.cfg` files.
368
369 ### Where _Black_ looks for the file
370
371 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
372 all files and directories passed on the command line. If it's not there, it looks in
373 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
374 `.hg` directory, or the root of the file system, whichever comes first.
375
376 If you're formatting standard input, _Black_ will look for configuration starting from
377 the current working directory.
378
379 You can use a "global" configuration, stored in a specific location in your home
380 directory. This will be used as a fallback configuration, that is, it will be used if
381 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
382 operating system, this configuration file should be stored as:
383
384 - Windows: `~\.black`
385 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
386   `XDG_CONFIG_HOME` environment variable is not set)
387
388 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
389 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
390 refers to the path to your home directory. On Windows, this will be something like
391 `C:\\Users\UserName`.
392
393 You can also explicitly specify the path to a particular file that you want with
394 `--config`. In this situation _Black_ will not look for any other file.
395
396 If you're running with `--verbose`, you will see a blue message if a file was found and
397 used.
398
399 Please note `blackd` will not use `pyproject.toml` configuration.
400
401 ### Configuration format
402
403 As the file extension suggests, `pyproject.toml` is a
404 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
405 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
406 same as long names of options on the command line.
407
408 Note that you have to use single-quoted strings in TOML for regular expressions. It's
409 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
410 expressions by Black. Use `[ ]` to denote a significant space character.
411
412 <details>
413 <summary>Example <code>pyproject.toml</code></summary>
414
415 ```toml
416 [tool.black]
417 line-length = 88
418 target-version = ['py37']
419 include = '\.pyi?$'
420 # 'extend-exclude' excludes files or directories in addition to the defaults
421 extend-exclude = '''
422 # A regex preceded with ^/ will apply only to files and directories
423 # in the root of the project.
424 (
425   ^/foo.py    # exclude a file named foo.py in the root of the project
426   | .*_pb2.py  # exclude autogenerated Protocol Buffer files anywhere in the project
427 )
428 '''
429 ```
430
431 </details>
432
433 ### Lookup hierarchy
434
435 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
436 override those defaults. Finally, options provided by the user on the command line
437 override both.
438
439 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
440 look for multiple files, and doesn't compose configuration from different levels of the
441 file hierarchy.
442
443 ## Next steps
444
445 A good next step would be configuring auto-discovery so `black .` is all you need
446 instead of laborously listing every file or directory. You can get started by heading
447 over to [File collection and discovery](./file_collection_and_discovery.md).
448
449 Another good choice would be setting up an
450 [integration with your editor](../integrations/editors.md) of choice or with
451 [pre-commit for source version control](../integrations/source_version_control.md).