]> 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:

57fafd87654d5834306828dfe77933465f299272
[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-version = ["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.9.1 (compiled: yes)
197 $ black --required-version 23.9.1 -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. This can also be specified via the
250 `BLACK_NUM_WORKERS` environment variable.
251
252 #### `-q`, `--quiet`
253
254 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critical output.
255 Error messages will still be emitted (which can silenced by `2>/dev/null`).
256
257 ```console
258 $ black src/ -q
259 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
260 ```
261
262 #### `-v`, `--verbose`
263
264 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
265 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
266 configuration file, a blue message detailing which one it is using will be emitted.
267
268 ```console
269 $ black src/ -v
270 Using configuration from /tmp/pyproject.toml.
271 src/blib2to3 ignored: matches the --extend-exclude regular expression
272 src/_black_version.py wasn't modified on disk since last run.
273 src/black/__main__.py wasn't modified on disk since last run.
274 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
275 reformatted src/black_primer/lib.py
276 reformatted src/blackd/__init__.py
277 reformatted src/black/__init__.py
278 Oh no! 💥 💔 💥
279 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
280 ```
281
282 #### `--version`
283
284 You can check the version of _Black_ you have installed using the `--version` flag.
285
286 ```console
287 $ black --version
288 black, 23.9.1
289 ```
290
291 #### `--config`
292
293 Read configuration options from a configuration file. See
294 [below](#configuration-via-a-file) for more details on the configuration file.
295
296 #### `-h`, `--help`
297
298 Show available command-line options and exit.
299
300 ### Environment variable options
301
302 _Black_ supports the following configuration via environment variables.
303
304 #### `BLACK_CACHE_DIR`
305
306 The directory where _Black_ should store its cache.
307
308 #### `BLACK_NUM_WORKERS`
309
310 The number of parallel workers _Black_ should use. The command line option `-W` /
311 `--workers` takes precedence over this environment variable.
312
313 ### Code input alternatives
314
315 _Black_ supports formatting code via stdin, with the result being printed to stdout.
316 Just let _Black_ know with `-` as the path.
317
318 ```console
319 $ echo "print ( 'hello, world' )" | black -
320 print("hello, world")
321 reformatted -
322 All done! ✨ 🍰 ✨
323 1 file reformatted.
324 ```
325
326 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
327 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
328 option on some editors that rely on using stdin.
329
330 You can also pass code as a string using the `-c` / `--code` option.
331
332 ### Writeback and reporting
333
334 By default _Black_ reformats the files given and/or found in place. Sometimes you need
335 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
336
337 There's two variations to this mode that are independently enabled by their respective
338 flags:
339
340 - `--check` (exit with code 1 if any file would be reformatted)
341 - `--diff` (print a diff instead of reformatting files)
342
343 Both variations can be enabled at once.
344
345 ### Output verbosity
346
347 _Black_ in general tries to produce the right amount of output, balancing between
348 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
349 plus a short summary.
350
351 ```console
352 $ black src/
353 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
354 reformatted src/black_primer/lib.py
355 reformatted src/blackd/__init__.py
356 reformatted src/black/__init__.py
357 Oh no! 💥 💔 💥
358 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
359 ```
360
361 The `--quiet` and `--verbose` flags control output verbosity.
362
363 ## Configuration via a file
364
365 _Black_ is able to read project-specific default values for its command line options
366 from a `pyproject.toml` file. This is especially useful for specifying custom
367 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
368 project.
369
370 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
371 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
372 code in compliance with many other _Black_ formatted projects.
373
374 ### What on Earth is a `pyproject.toml` file?
375
376 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
377 configuration file to store build system requirements for Python projects. With the help
378 of tools like [Poetry](https://python-poetry.org/),
379 [Flit](https://flit.readthedocs.io/en/latest/), or
380 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
381 `setup.cfg` files.
382
383 ### Where _Black_ looks for the file
384
385 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
386 all files and directories passed on the command line. If it's not there, it looks in
387 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
388 `.hg` directory, or the root of the file system, whichever comes first.
389
390 If you're formatting standard input, _Black_ will look for configuration starting from
391 the current working directory.
392
393 You can use a "global" configuration, stored in a specific location in your home
394 directory. This will be used as a fallback configuration, that is, it will be used if
395 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
396 operating system, this configuration file should be stored as:
397
398 - Windows: `~\.black`
399 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
400   `XDG_CONFIG_HOME` environment variable is not set)
401
402 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
403 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
404 refers to the path to your home directory. On Windows, this will be something like
405 `C:\\Users\UserName`.
406
407 You can also explicitly specify the path to a particular file that you want with
408 `--config`. In this situation _Black_ will not look for any other file.
409
410 If you're running with `--verbose`, you will see a blue message if a file was found and
411 used.
412
413 Please note `blackd` will not use `pyproject.toml` configuration.
414
415 ### Configuration format
416
417 As the file extension suggests, `pyproject.toml` is a
418 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
419 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
420 same as long names of options on the command line.
421
422 Note that you have to use single-quoted strings in TOML for regular expressions. It's
423 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
424 expressions by Black. Use `[ ]` to denote a significant space character.
425
426 <details>
427 <summary>Example <code>pyproject.toml</code></summary>
428
429 ```toml
430 [tool.black]
431 line-length = 88
432 target-version = ['py37']
433 include = '\.pyi?$'
434 # 'extend-exclude' excludes files or directories in addition to the defaults
435 extend-exclude = '''
436 # A regex preceded with ^/ will apply only to files and directories
437 # in the root of the project.
438 (
439   ^/foo.py    # exclude a file named foo.py in the root of the project
440   | .*_pb2.py  # exclude autogenerated Protocol Buffer files anywhere in the project
441 )
442 '''
443 ```
444
445 </details>
446
447 ### Lookup hierarchy
448
449 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
450 override those defaults. Finally, options provided by the user on the command line
451 override both.
452
453 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
454 look for multiple files, and doesn't compose configuration from different levels of the
455 file hierarchy.
456
457 ## Next steps
458
459 A good next step would be configuring auto-discovery so `black .` is all you need
460 instead of laborously listing every file or directory. You can get started by heading
461 over to [File collection and discovery](./file_collection_and_discovery.md).
462
463 Another good choice would be setting up an
464 [integration with your editor](../integrations/editors.md) of choice or with
465 [pre-commit for source version control](../integrations/source_version_control.md).