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

Prepare release 23.3.0 (#3625)
[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 expanding the view below or by running
30 `black --help`. While _Black_ has quite a few knobs these days, it is still opinionated
31 so style options are deliberately limited and rarely added.
32
33 <details>
34
35 <summary>CLI reference</summary>
36
37 ```{program-output} black --help
38
39 ```
40
41 </details>
42
43 Note that all command-line options listed above can also be configured using a
44 `pyproject.toml` file (more on that below).
45
46 ### Code input alternatives
47
48 #### Standard Input
49
50 _Black_ supports formatting code via stdin, with the result being printed to stdout.
51 Just let _Black_ know with `-` as the path.
52
53 ```console
54 $ echo "print ( 'hello, world' )" | black -
55 print("hello, world")
56 reformatted -
57 All done! ✨ 🍰 ✨
58 1 file reformatted.
59 ```
60
61 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
62 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
63 option on some editors that rely on using stdin.
64
65 #### As a string
66
67 You can also pass code as a string using the `-c` / `--code` option.
68
69 ```console
70 $ black --code "print ( 'hello, world' )"
71 print("hello, world")
72 ```
73
74 ### Writeback and reporting
75
76 By default _Black_ reformats the files given and/or found in place. Sometimes you need
77 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
78
79 There's two variations to this mode that are independently enabled by their respective
80 flags. Both variations can be enabled at once.
81
82 (labels/exit-code)=
83
84 #### Exit code
85
86 Passing `--check` will make _Black_ exit with:
87
88 - code 0 if nothing would change;
89 - code 1 if some files would be reformatted; or
90 - code 123 if there was an internal error
91
92 ```console
93 $ black test.py --check
94 All done! ✨ 🍰 ✨
95 1 file would be left unchanged.
96 $ echo $?
97 0
98
99 $ black test.py --check
100 would reformat test.py
101 Oh no! 💥 💔 💥
102 1 file would be reformatted.
103 $ echo $?
104 1
105
106 $ black test.py --check
107 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
108 Oh no! 💥 💔 💥
109 1 file would fail to reformat.
110 $ echo $?
111 123
112 ```
113
114 #### Diffs
115
116 Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_
117 would've made. They are printed to stdout so capturing them is simple.
118
119 If you'd like colored diffs, you can enable them with the `--color`.
120
121 ```console
122 $ black test.py --diff
123 --- test.py     2021-03-08 22:23:40.848954 +0000
124 +++ test.py     2021-03-08 22:23:47.126319 +0000
125 @@ -1 +1 @@
126 -print ( 'hello, world' )
127 +print("hello, world")
128 would reformat test.py
129 All done! ✨ 🍰 ✨
130 1 file would be reformatted.
131 ```
132
133 ### Output verbosity
134
135 _Black_ in general tries to produce the right amount of output, balancing between
136 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
137 plus a short summary.
138
139 ```console
140 $ black src/
141 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
142 reformatted src/black_primer/lib.py
143 reformatted src/blackd/__init__.py
144 reformatted src/black/__init__.py
145 Oh no! 💥 💔 💥
146 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
147 ```
148
149 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
150 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
151 configuration file, a blue message detailing which one it is using will be emitted.
152
153 ```console
154 $ black src/ -v
155 Using configuration from /tmp/pyproject.toml.
156 src/blib2to3 ignored: matches the --extend-exclude regular expression
157 src/_black_version.py wasn't modified on disk since last run.
158 src/black/__main__.py wasn't modified on disk since last run.
159 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
160 reformatted src/black_primer/lib.py
161 reformatted src/blackd/__init__.py
162 reformatted src/black/__init__.py
163 Oh no! 💥 💔 💥
164 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
165 ```
166
167 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critial output.
168 Error messages will still be emitted (which can silenced by `2>/dev/null`).
169
170 ```console
171 $ black src/ -q
172 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
173 ```
174
175 ### Versions
176
177 You can check the version of _Black_ you have installed using the `--version` flag.
178
179 ```console
180 $ black --version
181 black, version 23.3.0
182 ```
183
184 An option to require a specific version to be running is also provided.
185
186 ```console
187 $ black --required-version 21.9b0 -c "format = 'this'"
188 format = "this"
189 $ black --required-version 31.5b2 -c "still = 'beta?!'"
190 Oh no! 💥 💔 💥 The required version does not match the running version!
191 ```
192
193 This is useful for example when running _Black_ in multiple environments that haven't
194 necessarily installed the correct version. This option can be set in a configuration
195 file for consistent results across environments.
196
197 ## Configuration via a file
198
199 _Black_ is able to read project-specific default values for its command line options
200 from a `pyproject.toml` file. This is especially useful for specifying custom
201 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
202 project.
203
204 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
205 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
206 code in compliance with many other _Black_ formatted projects.
207
208 ### What on Earth is a `pyproject.toml` file?
209
210 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
211 configuration file to store build system requirements for Python projects. With the help
212 of tools like [Poetry](https://python-poetry.org/),
213 [Flit](https://flit.readthedocs.io/en/latest/), or
214 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
215 `setup.cfg` files.
216
217 ### Where _Black_ looks for the file
218
219 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
220 all files and directories passed on the command line. If it's not there, it looks in
221 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
222 `.hg` directory, or the root of the file system, whichever comes first.
223
224 If you're formatting standard input, _Black_ will look for configuration starting from
225 the current working directory.
226
227 You can use a "global" configuration, stored in a specific location in your home
228 directory. This will be used as a fallback configuration, that is, it will be used if
229 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
230 operating system, this configuration file should be stored as:
231
232 - Windows: `~\.black`
233 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
234   `XDG_CONFIG_HOME` environment variable is not set)
235
236 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
237 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
238 refers to the path to your home directory. On Windows, this will be something like
239 `C:\\Users\UserName`.
240
241 You can also explicitly specify the path to a particular file that you want with
242 `--config`. In this situation _Black_ will not look for any other file.
243
244 If you're running with `--verbose`, you will see a blue message if a file was found and
245 used.
246
247 Please note `blackd` will not use `pyproject.toml` configuration.
248
249 ### Configuration format
250
251 As the file extension suggests, `pyproject.toml` is a
252 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
253 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
254 same as long names of options on the command line.
255
256 Note that you have to use single-quoted strings in TOML for regular expressions. It's
257 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
258 expressions by Black. Use `[ ]` to denote a significant space character.
259
260 <details>
261 <summary>Example <code>pyproject.toml</code></summary>
262
263 ```toml
264 [tool.black]
265 line-length = 88
266 target-version = ['py37']
267 include = '\.pyi?$'
268 # 'extend-exclude' excludes files or directories in addition to the defaults
269 extend-exclude = '''
270 # A regex preceded with ^/ will apply only to files and directories
271 # in the root of the project.
272 (
273   ^/foo.py    # exclude a file named foo.py in the root of the project
274   | .*_pb2.py  # exclude autogenerated Protocol Buffer files anywhere in the project
275 )
276 '''
277 ```
278
279 </details>
280
281 ### Lookup hierarchy
282
283 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
284 override those defaults. Finally, options provided by the user on the command line
285 override both.
286
287 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
288 look for multiple files, and doesn't compose configuration from different levels of the
289 file hierarchy.
290
291 ## Next steps
292
293 A good next step would be configuring auto-discovery so `black .` is all you need
294 instead of laborously listing every file or directory. You can get started by heading
295 over to [File collection and discovery](./file_collection_and_discovery.md).
296
297 Another good choice would be setting up an
298 [integration with your editor](../integrations/editors.md) of choice or with
299 [pre-commit for source version control](../integrations/source_version_control.md).