feat(python): apply Code Style › Python to Ruff and Black (#5378)

Editor › Code Style › Python has indent, tab character and hard wrap, but Ruff and Black ignored them: without a configuration of their own they always formatted with 4 spaces at 88 columns, whatever the editor used. Now, when no Ruff configuration applies to the file (`ruff.toml`, `.ruff.toml` or `pyproject.toml` with `[tool.ruff]` in its folder or above, the user's Ruff configuration, or the configured Ruff configuration directory), Ruff gets the indentation and line length the editor uses, as `--config line-length / indent-width / format.indent-style`: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the values set on the page. Black, without `[tool.black]` in its project (found as Black finds it) and without a user configuration where Black would read one, gets the line length as `--line-length` (it has no indentation settings). Values set in neither place are not passed: the global hard wrap (120) is not Ruff's or Black's default (88), so existing projects keep formatting as before. The page says when these values apply.

Also adds Black as a selectable Python formatter (#5340's commits, which this branch was stacked on).

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-24 06:30:41 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent 558a98e74e
commit 68c4fe60ec
20 changed files with 636 additions and 68 deletions
+3 -1
View File
@@ -92,7 +92,9 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
### 格式化
**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时运行**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。
**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时运行**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。项目和用户配置里都没有时,Ruff 按编辑器使用的缩进和行宽格式化:先看文件的 `.editorconfig`(`indent_size`、`indent_style`、`max_line_length`),再看 **设置 › 编辑器 › 代码样式 › Python** 中设置的缩进、制表符和硬换行。两处都没设置的值不会传给 Ruff,Ruff 仍用自己的默认值(4 个空格、88 列)。
在含 `[tool.black]` 表的 `pyproject.toml` 所在目录及其子目录中,或在 **设置 › 语言和框架 › Black 格式化工具** 中把 **格式化工具** 设为 Black 后,由 Black 代替 Ruff 格式化。Black 自己读取 `[tool.black]` 中的选项。IDE 优先使用项目解释器环境中的 `black`,其次是工具文件夹或 `PATH` 中的;都没有安装时,重新格式化代码会提示安装。在查找操作中运行 **使用 Black 重新格式化**,无论项目用什么格式化工具,都会用 Black 格式化。Black 自己的 **保存时运行** 或编辑器的 **保存时格式化** 打开时,保存文件会运行 Black。没有 `[tool.black]`(按 Black 的方式查找:跳过不含它的 `pyproject.toml`,一直到仓库根目录)或用户配置时,Black 也使用这个行宽。Black 配置排除的文件(`force-exclude`)保持不变;23.11 之前的 Black 不能格式化选区,会格式化整个文件。
**优化导入**(`⌃⌥O` / `Ctrl+Alt+O`)对导入排序。在 Ruff 配置所在目录及其子目录中由 Ruff 服务器完成,未使用的导入保持不变(由 Ruff 的一键修复删除)。其他位置由 IDE 对文件运行 `ruff check --extend-select I --fixable I,F401 --fix`,除非 Ruff 规则不包含 F401,否则同时删除未使用的导入;需要安装 Ruff。保存时、提交前和代码清理中的优化导入也是如此。