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
+9 -1
View File
@@ -1208,6 +1208,7 @@ pub struct LanguagesSettings {
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
@@ -1235,6 +1236,10 @@ impl Default for LanguagesSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
black: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
java: JavaSettings::default(),
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
@@ -1304,6 +1309,7 @@ impl LanguagesSettings {
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
}
}
@@ -1316,6 +1322,7 @@ pub enum ExternalFormatter {
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1326,6 +1333,7 @@ impl ExternalFormatter {
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
Self::Black => "black",
}
}
}
@@ -1334,7 +1342,7 @@ impl ExternalFormatter {
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats.
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
+365 -48
View File
@@ -31,9 +31,105 @@ fn biome_formats(file: &Path) -> bool {
}
}
/// `tool` installed in the environment of the interpreter nearest to `near` (`svc/.venv/bin/ruff`,
/// or `Scripts` in conda and pixi environments on Windows). A project that pins its own Ruff
/// formats with it, as its language server runs it, before the IDE's copy.
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
fn black_pyproject(file: &Path) -> Option<PathBuf> {
let mut dirs = file.parent()?.ancestors();
let root = dirs
.find(|d| {
d.join(".git").exists()
|| d.join(".hg").is_dir()
|| ide_sdk::apply::toml_has_table(&d.join("pyproject.toml"), "tool.black")
})
.or_else(|| file.parent()?.ancestors().last())?;
Some(root.join("pyproject.toml")).filter(|p| p.is_file())
}
/// Black formats files whose project configures it (`[tool.black]`).
fn black_configured(file: &Path) -> bool {
black_pyproject(file).is_some_and(|p| ide_sdk::apply::toml_has_table(&p, "tool.black"))
}
/// The single user configuration directory the formatter searches.
fn user_config_dir(tool: &str, cwd: &Path) -> Option<PathBuf> {
if cfg!(windows) {
return if tool == "black" { dirs::home_dir() } else { dirs::config_dir() };
}
let xdg = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
xdg_user_config_dir(tool, cwd, xdg.as_deref(), dirs::home_dir().as_deref())
}
fn xdg_user_config_dir(tool: &str, cwd: &Path, xdg: Option<&Path>, home: Option<&Path>) -> Option<PathBuf> {
if let Some(dir) = xdg.filter(|dir| tool == "black" || dir.is_absolute()) {
if let Ok(relative) = dir.strip_prefix("~") {
return home.map(|home| home.join(relative));
}
return Some(cwd.join(dir));
}
home.map(|home| home.join(".config"))
}
fn user_configured(tool: &str, dir: Option<&Path>) -> bool {
let Some(dir) = dir else { return false };
let names: &[&str] = match tool {
"ruff" => &["ruff/.ruff.toml", "ruff/ruff.toml", "ruff/pyproject.toml"],
"black" if cfg!(windows) => &[".black"],
"black" => &["black"],
_ => &[],
};
names.iter().any(|name| dir.join(name).is_file())
}
/// Whether Ruff finds a configuration of the project for `file`: `ruff.toml`, `.ruff.toml` or a
/// `pyproject.toml` with `[tool.ruff]` in its folder or above.
fn ruff_project_configured(file: &Path) -> bool {
file.parent().into_iter().flat_map(Path::ancestors).any(|dir| {
dir.join("ruff.toml").is_file()
|| dir.join(".ruff.toml").is_file()
|| ide_sdk::apply::toml_has_table(&dir.join("pyproject.toml"), "tool.ruff")
})
}
/// The indentation and line length for `tool`, unless a configuration of the project or the user
/// decides them (or the Ruff configuration directory is set): the file's `.editorconfig`, then
/// what was set on the Code Style › Python page, as the editor indents.
fn python_style_for(
tool: &str,
file: &Path,
configured: bool,
settings: &Settings,
editorconfig: Option<&ide_workspace::editorconfig::EditorConfigProps>,
user_dir: Option<&Path>,
) -> formatter::PythonStyle {
let has_config = configured
|| match tool {
"ruff" => ruff_project_configured(file) || user_configured("ruff", user_dir),
// Black reads the user's configuration only when its project root has no pyproject.toml.
"black" => match black_pyproject(file) {
Some(pyproject) => ide_sdk::apply::toml_has_table(&pyproject, "tool.black"),
None => user_configured("black", user_dir),
},
_ => true,
};
if has_config {
return formatter::PythonStyle::default();
}
// Only what was set: the global hard wrap (120) is not Ruff's or Black's default (88).
let page = settings.editor.code_style.languages.get("python");
let ec = editorconfig;
formatter::PythonStyle {
line_length: ec.and_then(|e| e.max_line_length).or(page.and_then(|s| s.hard_wrap_at)),
indent_width: ec.and_then(|e| e.indent_size.or(e.tab_width)).or(page.and_then(|s| s.indent.or(s.tab_size))),
use_tabs: ec
.and_then(|e| e.indent_style)
.map(|style| style == ide_workspace::editorconfig::IndentStyle::Tab)
.or(page.and_then(|s| s.use_tab)),
}
}
/// `tool` installed in the environment of the interpreter nearest to `near` (`svc/.venv/bin/ruff` or
/// `svc/.venv/bin/black`), or in `Scripts` for conda and pixi environments on Windows.
fn interpreter_tool(root: &Path, near: Option<&Path>, settings: &Settings, tool: &str) -> Option<PathBuf> {
let python = ide_sdk::apply::python_interpreter_near(root, near, settings)?;
let dir = python.parent()?;
@@ -41,18 +137,25 @@ fn interpreter_tool(root: &Path, near: Option<&Path>, settings: &Settings, tool:
[dir.join(&exe), dir.join("Scripts").join(&exe)].into_iter().find(|p| p.is_file())
}
/// Formatters print nothing for a file their configuration excludes (Black's `force-exclude`):
/// that output must not replace the file.
fn excluded_output(text: &str, formatted: &str) -> bool {
formatted.is_empty() && !text.trim().is_empty()
}
fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) -> bool {
match language.formatter.as_ref().map(|f| f.tool.as_str()) {
Some("prettier") if tool == ExternalFormatter::Biome => BIOME_LANGUAGES.contains(&language.id.as_str()),
Some("prettier") => matches!(tool, ExternalFormatter::Prettier | ExternalFormatter::Oxfmt),
Some("ruff") => tool == ExternalFormatter::Ruff,
Some("ruff") => matches!(tool, ExternalFormatter::Ruff | ExternalFormatter::Black),
_ => false,
}
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, or Ruff). Ruff is
/// the base formatter for Python; Biome, then oxfmt, can replace Prettier for their
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
/// then oxfmt, can replace Prettier for their
/// languages when configured or selected. A tool that cannot format the language is
/// rejected even when explicitly requested.
fn external_tool(
@@ -61,7 +164,7 @@ fn external_tool(
file: &Path,
settings: &LanguagesSettings,
) -> IdeResult<Option<ExternalFormatter>> {
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
let Some(language) = language.filter(|l| l.formatter.is_some()) else {
return match forced {
Some(tool) => Err(IdeError::invalid(format!(
@@ -85,7 +188,11 @@ fn external_tool(
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(enabled(Ruff).then_some(Ruff));
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
} else {
enabled(Ruff).then_some(Ruff)
});
}
let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
let biome = enabled(Biome) && supports_external_format(language, Biome);
@@ -386,8 +493,10 @@ async fn provider_edits(
return Ok(Some(edits));
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
if let Some(tool) = selected
&& options.tool.is_none()
&& tool != ExternalFormatter::Black
&& !settings.languages.formatter(tool).prefer
&& match doc {
Some(doc) => project.lsp.can_format(doc).await?,
@@ -410,7 +519,10 @@ async fn provider_edits(
.map_err(|e| IdeError::internal(e.to_string()));
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
// Black takes over from the language server in its projects, so Format on save runs it too.
let runs_on_save =
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
if options.on_save && !runs_on_save {
return Ok(None);
}
host.require_trust(window)?;
@@ -421,18 +533,20 @@ async fn provider_edits(
let tool = selected.name();
let name = formatter::display_name(tool);
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
if custom.is_none() && selected == ExternalFormatter::Ruff {
if custom.is_none() && matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let (root, near, settings) =
(project.root.clone(), snap.path.parent().map(Path::to_path_buf), settings.clone());
custom = tokio::task::spawn_blocking(move || interpreter_tool(&root, near.as_deref(), &settings, "ruff"))
custom = tokio::task::spawn_blocking(move || interpreter_tool(&root, near.as_deref(), &settings, tool))
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let tools = Tools::new(&host.local_data_dir);
let whole_selection = range.is_some() && !formatter::supports_range(tool, &config);
let unsupported_range = range.is_some() && !formatter::supports_range(tool, &config);
let project_root = project.root.clone();
let configuration_directory = settings.languages.ruff.configuration_directory.clone();
let edits: IdeResult<Vec<TextEdit>> = tokio::task::spawn_blocking(move || {
let style_settings = settings.clone();
let documents = project.documents.clone();
let result: IdeResult<(Vec<TextEdit>, bool, bool)> = tokio::task::spawn_blocking(move || {
let text = ide_text::Document::new(&snap.text);
let range = range.map(|range| format_range(&text, range));
let config_file = if tool == "ruff" {
@@ -440,32 +554,80 @@ async fn provider_edits(
} else {
None
};
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
let dir = snap.path.parent().ok_or_else(|| IdeError::invalid(format!("{name}: file has no directory")))?;
command.current_dir(dir);
command.args(formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
));
let formatted = formatter::run(tool, command, &snap.text, &Default::default())?;
Ok(diff_edits(&text, &formatted))
let style = if matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let editorconfig = style_settings
.editor
.code_style
.editorconfig
.then(|| documents.editorconfig().resolve(&snap.path))
.flatten();
python_style_for(
tool,
&snap.path,
config_file.is_some(),
&style_settings,
editorconfig.as_ref(),
user_config_dir(tool, dir).as_deref(),
)
} else {
formatter::PythonStyle::default()
};
let run = |range| {
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
command.current_dir(dir);
let args = formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
);
command.args(formatter::with_python_style(tool, args, style));
formatter::run(tool, command, &snap.text, &Default::default())
};
let mut old_black = false;
let formatted = match run(range) {
// Black before 23.11 has no `--line-ranges`: format the whole file instead.
Err(e) if tool == "black" && range.is_some() && e.message.contains("--line-ranges") => {
old_black = true;
run(None)?
}
result => result?,
};
if excluded_output(&snap.text, &formatted) {
return Ok((Vec::new(), false, true));
}
let edits = diff_edits(&text, &formatted);
Ok((edits, old_black, false))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
if edits.is_ok() && whole_selection {
let (edits, old_black, excluded) = match result {
Ok((edits, old_black, excluded)) => (Ok(edits), old_black, excluded),
Err(e) => (Err(e), false, false),
};
// Notification titles are translated, and the catalog has "Black" as the colour.
let title = if selected == ExternalFormatter::Black { "Black formatter" } else { name };
if excluded && !options.on_save {
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Info,
title: name.into(),
body: Some(format!(
"{name} does not support selection formatting for this language; formatted the whole file"
)),
title: title.into(),
body: Some(format!("{name} left the file unchanged: its configuration excludes it")),
});
}
let whole_selection = if old_black {
Some("This Black cannot format a selection (Black 23.11 or later can); formatted the whole file".to_owned())
} else {
(edits.is_ok() && unsupported_range).then(|| {
format!("{name} does not support selection formatting for this language; formatted the whole file")
})
};
if let Some(body) = whole_selection {
project.sink.emit(IdeEvent::Notify { level: NotifyLevel::Info, title: title.into(), body: Some(body) });
}
edits.map(Some).map_err(|e| e.with_tool(tool))
}
@@ -518,23 +680,7 @@ pub async fn python_import_edits(
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ruff_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
let settings = Settings::default();
let near = root.join("svc/src");
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), None);
std::fs::write(bin.join(exe("ruff")), "").unwrap();
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), Some(bin.join(exe("ruff"))));
}
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
@@ -579,6 +725,177 @@ mod tests {
assert_eq!(oxfmt.message, "oxfmt cannot format Python files");
let biome = tool(Some(Biome), "python", file, &settings).unwrap_err();
assert_eq!(biome.message, "Biome cannot format Python files");
assert_eq!(tool(Some(Black), "python", file, &settings).unwrap(), Some(Black));
let black = tool(Some(Black), "typescript", Path::new("/project/app.ts"), &settings).unwrap_err();
assert_eq!(black.message, "Black cannot format TypeScript files");
}
#[test]
#[cfg(not(windows))]
fn an_xdg_override_hides_fallback_python_formatter_configs() {
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
let home = cwd.join("home");
let fallback = home.join(".config");
let xdg = cwd.join("config override");
for (tool, name) in [("ruff", "ruff/ruff.toml"), ("black", "black")] {
let config = fallback.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
let probe = |xdg| xdg_user_config_dir(tool, cwd, xdg, Some(&home));
assert!(user_configured(tool, probe(None).as_deref()), "{tool} should find its default config");
assert!(!user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should skip its default config");
let config = xdg.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
assert!(user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should find its XDG config");
}
let relative = Some(Path::new("config override"));
assert_eq!(xdg_user_config_dir("ruff", cwd, relative, Some(&home)), Some(fallback));
assert_eq!(xdg_user_config_dir("black", cwd, relative, Some(&home)), Some(xdg));
assert_eq!(xdg_user_config_dir("black", cwd, Some(Path::new("~/alt")), Some(&home)), Some(home.join("alt")));
}
#[test]
fn code_style_reaches_ruff_and_black_only_without_their_configuration() {
use ide_workspace::editorconfig::{EditorConfigProps, IndentStyle};
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repo");
let user = dir.path().join("user config");
std::fs::create_dir_all(root.join("app/src")).unwrap();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(user.join("ruff")).unwrap();
let file = root.join("app/src/main.py");
let mut settings = Settings::default();
let style = |tool, settings: &Settings, editorconfig: Option<&EditorConfigProps>| {
python_style_for(tool, &file, false, settings, editorconfig, Some(&user))
};
let none = formatter::PythonStyle::default();
// Nothing set: the tools keep their defaults.
assert_eq!(style("ruff", &settings, None), none);
let page = ide_core::editor_settings::LanguageCodeStyle {
hard_wrap_at: Some(100),
tab_size: Some(2),
..Default::default()
};
settings.editor.code_style.languages.insert("python".into(), page);
let set = formatter::PythonStyle { line_length: Some(100), indent_width: Some(2), use_tabs: None };
assert_eq!(style("ruff", &settings, None), set);
assert_eq!(style("black", &settings, None), set);
assert_eq!(python_style_for("ruff", &file, true, &settings, None, Some(&user)), none);
// The file's .editorconfig wins over the page, as in the editor.
let editorconfig =
EditorConfigProps { indent_size: Some(4), indent_style: Some(IndentStyle::Space), ..Default::default() };
let indented = formatter::PythonStyle { line_length: Some(100), indent_width: Some(4), use_tabs: Some(false) };
assert_eq!(style("ruff", &settings, Some(&editorconfig)), indented);
// The user's configurations: Ruff's always counts, Black's only when the project root
// (here the repository) has no pyproject.toml.
let (black_config, ignored_black_config) =
if cfg!(windows) { (".black", "black") } else { ("black", ".black") };
std::fs::write(user.join(ignored_black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join(black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join("ruff/ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
std::fs::remove_file(user.join("ruff/ruff.toml")).unwrap();
// The project's configurations.
std::fs::write(root.join("app/pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join(".ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
}
#[test]
fn empty_output_for_a_file_with_code_is_an_exclusion_not_an_empty_file() {
assert!(excluded_output("x = 1\n", ""));
assert!(!excluded_output("\n\n", ""));
assert!(!excluded_output("x = 1\n", "x = 1\n"));
}
#[test]
fn ruff_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
let settings = Settings::default();
let near = root.join("svc/src");
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), None);
std::fs::write(bin.join(exe("ruff")), "").unwrap();
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), Some(bin.join(exe("ruff"))));
}
#[test]
fn black_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\n").unwrap();
let settings = Settings::default();
assert_eq!(interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"), None);
std::fs::write(bin.join(exe("black")), "").unwrap();
assert_eq!(
interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"),
Some(bin.join(exe("black")))
);
}
#[test]
fn black_config_or_preference_selects_black_for_python() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("svc/src")).unwrap();
std::fs::create_dir_all(root.join("api")).unwrap();
let (svc, api) = (root.join("svc/src/main.py"), root.join("api/main.py"));
let mut settings = LanguagesSettings::default();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Black));
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Ruff));
settings.black.prefer = true;
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Black));
settings.black.languages.clear();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
}
#[test]
fn black_finds_its_configuration_like_black_does() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().join("repo");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(repo.join("pkg/src")).unwrap();
let file = repo.join("pkg/src/m.py");
assert_eq!(black_pyproject(&file), None);
// A pyproject without [tool.black] is passed over, up to the repository root.
std::fs::write(repo.join("pkg/pyproject.toml"), "[project]\nname = \"pkg\"\n").unwrap();
std::fs::write(repo.join("pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(black_configured(&file));
// The repository root's pyproject is Black's even without [tool.black]; nothing above counts.
std::fs::write(repo.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
std::fs::write(dir.path().join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(!black_configured(&file));
std::fs::write(repo.join("pkg/pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
}
#[test]
+2 -1
View File
@@ -31,7 +31,8 @@ pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
Some(if p.is_absolute() { p } else { root.join(p) })
}
fn toml_has_table(file: &Path, table: &str) -> bool {
/// Whether the TOML `file` has the dotted `table` (`tool.ruff`).
pub fn toml_has_table(file: &Path, table: &str) -> bool {
let Ok(text) = std::fs::read_to_string(file) else { return false };
let Ok(value) = toml::from_str::<toml::Value>(&text) else { return false };
table.split('.').try_fold(&value, |value, key| value.get(key)).is_some_and(toml::Value::is_table)
+99 -4
View File
@@ -9,7 +9,7 @@ use std::process::Command;
use std::time::Duration;
/// A selection to format. Offsets are UTF-16 code units for Prettier; the
/// one-based line and column values are Unicode code points for Ruff.
/// one-based line and column values are Unicode code points for Ruff (Black uses the lines).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FormatRange {
pub start_offset: u32,
@@ -62,9 +62,10 @@ fn package_bin(package: &Path, tool: &str) -> IdeResult<PathBuf> {
Ok(path)
}
/// Prettier and Ruff format ranges for some languages (`config.range`); oxfmt and Biome format whole files only.
/// Prettier, Ruff and Black format ranges for some languages (`config.range`); oxfmt and Biome
/// format whole files only.
pub fn supports_range(tool: &str, config: &FormatterConfig) -> bool {
matches!(tool, "prettier" | "ruff") && config.range
matches!(tool, "prettier" | "ruff" | "black") && config.range
}
fn is_formatter(tool: &str) -> bool {
@@ -128,7 +129,7 @@ impl Tools {
/// Every tool resolves its configuration itself. Prettier's project configuration
/// overrides the editor indentation passed here; oxfmt, Biome and Ruff read their own
/// configuration files. Ruff also discovers the nearest `pyproject.toml`,
/// `ruff.toml`, or `.ruff.toml` from the stdin filename.
/// `ruff.toml`, or `.ruff.toml` from the stdin filename, and Black its `pyproject.toml`.
pub fn arguments(
tool: &str,
config: &FormatterConfig,
@@ -155,6 +156,22 @@ pub fn arguments(
}
return args;
}
if tool == "black" {
args.extend(["--quiet".into(), "--stdin-filename".into(), file.as_os_str().to_owned()]);
if supports_range(tool, config)
&& let Some(range) = range
{
// Inclusive lines: a selection ending at the start of a line leaves that line out.
let end = if range.end_col == 1 && range.end_line > range.start_line {
range.end_line - 1
} else {
range.end_line
};
args.extend(["--line-ranges".into(), format!("{}-{}", range.start_line, end).into()]);
}
args.push("-".into());
return args;
}
if tool == "biome" {
// Biome finds its `biome.json` and ignore files from the file's path itself.
let mut path = OsString::from("--stdin-file-path=");
@@ -201,6 +218,36 @@ pub fn arguments(
args
}
/// The Code Style › Python values the user set, for a file without a Ruff or Black configuration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PythonStyle {
pub line_length: Option<u32>,
pub indent_width: Option<u32>,
pub use_tabs: Option<bool>,
}
/// [`arguments`] with `style` added as Ruff's `--config` overrides or Black's `--line-length`
/// (Black has no indentation settings).
pub fn with_python_style(tool: &str, mut args: Vec<OsString>, style: PythonStyle) -> Vec<OsString> {
let settings: Vec<OsString> = match tool {
"ruff" => [
style.line_length.map(|n| format!("line-length={n}")),
style.indent_width.map(|n| format!("indent-width={n}")),
style.use_tabs.map(|tabs| format!("format.indent-style=\"{}\"", if tabs { "tab" } else { "space" })),
]
.into_iter()
.flatten()
.flat_map(|setting| ["--config".into(), setting.into()])
.collect(),
"black" => style.line_length.map(|n| vec!["--line-length".into(), n.to_string().into()]).unwrap_or_default(),
_ => Vec::new(),
};
// Ruff's options follow its `format` subcommand.
let at = usize::from(tool == "ruff").min(args.len());
args.splice(at..at, settings);
args
}
/// `ruff check` that sorts the imports (I) of the text on stdin and removes the unused ones (F401)
/// and prints the result, for Optimize Imports where the Ruff server isn't running. Only those two
/// are fixed, and F401 only where the project's rules check it (it is in Ruff's defaults; an
@@ -444,6 +491,54 @@ mod tests {
assert!(!args.iter().any(|arg| arg == "--stdin-filepath"));
}
#[test]
fn python_style_becomes_ruff_overrides_or_blacks_line_length() {
let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true };
let file = Path::new("/project/main.py");
let style = PythonStyle { line_length: Some(100), indent_width: Some(2), use_tabs: Some(true) };
let args = |tool: &str, style| -> Vec<String> {
with_python_style(tool, arguments(tool, &config, file, 4, true, None, None), style)
.into_iter()
.map(|a| a.to_string_lossy().into_owned())
.collect()
};
assert_eq!(
args("ruff", style)[..7],
[
"format",
"--config",
"line-length=100",
"--config",
"indent-width=2",
"--config",
"format.indent-style=\"tab\""
]
);
assert_eq!(args("black", style)[..3], ["--line-length", "100", "--quiet"]);
assert_eq!(args("ruff", PythonStyle::default())[1], "--stdin-filename");
assert_eq!(args("black", PythonStyle { use_tabs: Some(true), ..Default::default() })[0], "--quiet");
}
#[test]
fn black_formats_stdin_with_inclusive_line_ranges() {
let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true };
let file = Path::new("/project/src/example.py");
let args = |range| -> Vec<String> {
arguments("black", &config, file, 4, true, range, None)
.into_iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect()
};
assert_eq!(args(None), ["--quiet", "--stdin-filename", "/project/src/example.py", "-"]);
let range = |end_line, end_col| {
Some(FormatRange { start_offset: 0, end_offset: 0, start_line: 2, start_col: 1, end_line, end_col })
};
assert_eq!(args(range(4, 1))[3..], ["--line-ranges", "2-3", "-"]);
assert_eq!(args(range(4, 6))[3..], ["--line-ranges", "2-4", "-"]);
assert_eq!(args(range(2, 1))[3..], ["--line-ranges", "2-2", "-"]);
assert!(supports_range("black", &config));
}
#[test]
fn ruff_organizes_imports_of_stdin_without_failing_on_what_it_cannot_fix() {
let file = Path::new("/project/src/example.py");
+11
View File
@@ -345,6 +345,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://docs.astral.sh/ruff/",
needs: &[],
},
ToolSpec {
name: "black",
display: "Black",
kind: Formatter,
commands: &["black"],
method: Method::PipVenv { package: "black" },
fallback: None,
version: ver("black"),
homepage: "https://black.readthedocs.io",
needs: &[],
},
ToolSpec {
name: "djlsp",
display: "Django Template LSP",
+53
View File
@@ -0,0 +1,53 @@
//! `cargo test -p ide-tools --test black -- --ignored --nocapture`
use ide_core::CancellationToken;
use ide_language::FormatterConfig;
use ide_tools::{Tools, formatter};
use std::path::Path;
fn format(
tools: &Tools,
path: &Path,
text: &str,
range: Option<formatter::FormatRange>,
) -> ide_core::IdeResult<String> {
let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true };
let mut cmd = tools.formatter_command("black", path, None)?;
cmd.current_dir(path.parent().unwrap());
cmd.args(formatter::arguments("black", &config, path, 4, true, range, None));
formatter::run("black", cmd, text, &CancellationToken::new())
}
#[test]
#[ignore = "requires black on PATH"]
fn real_black_reads_project_config_formats_stdin_ranges_and_exclusions() {
let temp = tempfile::tempdir().unwrap();
let tools = Tools::new(&temp.path().join("app-data"));
if tools.info("black", &[]).unwrap().status == ide_tools::ToolStatus::Missing {
eprintln!("SKIP real Black: not on PATH");
return;
}
let project = temp.path().join("project with spaces");
std::fs::create_dir_all(project.join("gen")).unwrap();
std::fs::write(project.join("pyproject.toml"), "[tool.black]\nline-length = 20\nforce-exclude = \"gen/\"\n")
.unwrap();
let path = project.join("example.py");
let output = format(&tools, &path, "x = {'a': 1, 'b': 2, 'c': 3}\n", None).unwrap();
assert_eq!(output, "x = {\n \"a\": 1,\n \"b\": 2,\n \"c\": 3,\n}\n");
assert!(!path.exists(), "formatting must never write the file");
let range = formatter::FormatRange {
start_offset: 0,
end_offset: 0,
start_line: 2,
start_col: 1,
end_line: 2,
end_col: 100,
};
let output = format(&tools, &path, "a = 1\nb = 2\n", Some(range)).unwrap();
assert_eq!(output, "a = 1\nb = 2\n");
// An excluded file comes back empty; the host keeps the document as it is.
let output = format(&tools, &project.join("gen/m.py"), "x = { 'a':1 }\n", None).unwrap();
assert_eq!(output, "");
}
+3 -1
View File
@@ -92,7 +92,9 @@ Other options on the page:
### Formatting
**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Run on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`.
**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Run on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`. When neither the project nor your user configuration has one, Ruff formats with the indentation and line length the editor uses: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the indent, tab character and hard wrap you set in **Settings › Editor › Code Style › Python**. Values set in neither are not passed, so Ruff keeps its own (4 spaces, 88 columns).
Black formats instead of Ruff below a `pyproject.toml` with a `[tool.black]` table, or everywhere when **Formatting provider** is set to Black in **Settings › Languages & Frameworks › Black formatter**. Black reads its `[tool.black]` options itself. The IDE runs the `black` of the project interpreter's environment, else the one in its tools folder or on `PATH`; when none is installed, Reformat Code offers to install it. **Reformat with Black** in Find Action formats with Black whatever the project uses. Black runs on save when its own **Run on save** or the editor's **Format on save** is on. Without a `[tool.black]` (looked up the way Black does: past a `pyproject.toml` without it, up to the repository root) or a user configuration, Black uses that line length too. Files Black's configuration excludes (`force-exclude`) are left unchanged, and Black before 23.11 formats the whole file instead of a selection.
**Optimize Imports** (`⌃⌥O` / `Ctrl+Alt+O`) sorts the imports. Below a Ruff configuration the Ruff server does it and leaves unused imports alone (Ruff's fix-all removes them). Elsewhere the IDE runs `ruff check --extend-select I --fixable I,F401 --fix` on the file, which also removes unused imports unless your Ruff rules leave out F401; Ruff must be installed. The same goes for Optimize imports on save, before commit and in Code Cleanup.
+1 -1
View File
@@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| Plugins | Plugins |
| Version Control | Commit; Confirmation; Directory Mappings; Issue Navigation; Log; Shelf; Git; GitHub |
| Build, Execution, Deployment | CMake; Gradle; Maven; Console; Debugger (Data Views, Stepping); Python Debugger; Run/Debug; Run Targets; Deployment (Options) |
| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; Ruff; Ruby; Rust; TypeScript |
| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; Ruff; Black formatter; Ruby; Rust; TypeScript |
| Tools | Agents (Chat); Terminal; Actions on Save; External Tools; SSH Configurations; MCP Server |
| Security | Project Trust |
+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。保存时、提交前和代码清理中的优化导入也是如此。
+1 -1
View File
@@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| 插件 | 插件 |
| 版本控制 | 提交;确认;目录映射;问题导航;日志;搁置;Git;GitHub |
| 构建、执行、部署 | CMake;Gradle;Maven;控制台;调试器(数据视图、单步执行);Python 调试器;运行/调试;运行目标;部署(选项) |
| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;Ruff;Ruby;Rust;TypeScript |
| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;Ruff;Black 格式化工具;Ruby;Rust;TypeScript |
| 工具 | 智能体(聊天);终端;保存时操作;外部工具;SSH 配置;MCP 服务器 |
| 安全 | 项目信任 |
+3 -2
View File
@@ -6702,9 +6702,9 @@ export type ExternalDiffSide = {
};
/** A formatter that runs outside the language servers, with its own settings group. */
export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "ruff";
export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "ruff" | "black";
/** An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. */
/** An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats. */
export type ExternalFormatterSettings = {
/** Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. */
path?: string,
@@ -8875,6 +8875,7 @@ export type LanguagesSettings = {
oxfmt?: ExternalFormatterSettings,
biome?: ExternalFormatterSettings,
ruff?: ExternalFormatterSettings,
black?: ExternalFormatterSettings,
java?: JavaSettings,
ruby?: RubySettings,
markdown?: MarkdownSettings,
+11 -2
View File
@@ -228,10 +228,12 @@ function editorAction(
/** Whether saving a `language` file formats it: Format on save, or Run on save of an external formatter. */
export function formatsOnSave(settings: Settings | null, language: string): boolean {
const { prettier, oxfmt, biome, ruff } = validateLanguages(settings?.languages);
const { prettier, oxfmt, biome, ruff, black } = validateLanguages(settings?.languages);
return (
!!settings?.editor?.formatOnSave ||
[prettier, oxfmt, biome, ruff].some((formatter) => formatter.runOnSave && formatter.languages.includes(language))
[prettier, oxfmt, biome, ruff, black].some(
(formatter) => formatter.runOnSave && formatter.languages.includes(language),
)
);
}
@@ -322,6 +324,13 @@ export function registerLspActions(): () => void {
(v) => formatDocument(v, { explicit: true, tool: "ruff" }),
{ keywords: ["format", "ruff", "python"] },
),
editorAction(
"code.reformatWithBlack",
"Reformat with Black",
"Code",
(v) => formatDocument(v, { explicit: true, tool: "black" }),
{ keywords: ["format", "black", "python"] },
),
editorAction("code.reformatDialog", "Reformat File…", "Code", (v) =>
reformatDialog(v, (view) => applyKindSilently(view, "source.organizeImports")),
),
+1
View File
@@ -178,6 +178,7 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise<Fo
oxfmt: { failed: "oxfmt formatting failed", timedOut: "oxfmt formatting timed out" },
biome: { failed: "Biome formatting failed", timedOut: "Biome formatting timed out" },
ruff: { failed: "Ruff formatting failed", timedOut: "Ruff formatting timed out" },
black: { failed: "Black formatting failed", timedOut: "Black formatting timed out" },
}[e.data.tool]
: undefined;
if (e instanceof IpcError && e.data?.type === "tool" && formatter) {
@@ -392,12 +392,19 @@ describe("language pages", () => {
const tree = buildPageTree(LANGUAGE_PAGES.map((p) => ({ ...p, component: p.component! })));
const langs = tree.find((n) => n.title === "Languages & Frameworks")!;
const python = langs.children.find((n) => n.title === "Python")!;
expect(python.children.map((n) => n.title)).toEqual(["All Interpreters", "Dependencies", "Docstrings", "Ruff"]);
expect(python.children.map((n) => n.title)).toEqual([
"All Interpreters",
"Dependencies",
"Docstrings",
"Ruff",
"Black formatter",
]);
expect(python.children.map((n) => n.key)).toEqual([
"python.interpreters",
"python.interpreter",
"python.docstrings",
"python.ruff",
"python.black",
]);
// The folder itself has no page body: it links to the pages below it.
expect(python.page?.component).toBeUndefined();
@@ -31,6 +31,7 @@ interface FormatterPageProps {
pathLabel: string;
pathHint?: string;
configurationDirectory?: boolean;
autoLabel?: string;
providerHint?: string;
saveHint: string;
}
@@ -41,6 +42,7 @@ function FormatterPage({
pathLabel,
pathHint = "Auto: nearest project node_modules, managed installation, then PATH. An explicit path overrides auto detection.",
configurationDirectory = false,
autoLabel = "Automatic (language server first)",
providerHint,
saveHint,
}: FormatterPageProps) {
@@ -62,7 +64,7 @@ function FormatterPage({
onChange={(v) => setPrefer(v === tool)}
aria-label="Formatting provider"
options={[
{ value: "auto", label: "Automatic (language server first)" },
{ value: "auto", label: autoLabel },
{ value: tool, label: name },
]}
/>
@@ -170,3 +172,17 @@ export function RuffPage() {
/>
);
}
export function BlackPage() {
return (
<FormatterPage
tool="black"
name="Black formatter"
pathLabel="Black path"
pathHint="Auto: the project interpreter's environment, managed installation, then PATH. An explicit path overrides auto detection."
autoLabel="Automatic (projects with [tool.black])"
providerHint="Black formats Python instead of Ruff below a pyproject.toml with [tool.black], or when it is the selected provider."
saveHint="Run Black on save for enabled languages when it is the selected formatting provider. Reformat code in Actions on Save also runs it."
/>
);
}
@@ -246,6 +246,13 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
<SchemeRow />
{lang.id === "java" && <JavaFormatter style={own} onChange={set} />}
<CodeStyleTabs tabs={tabs} />
{lang.id === "python" && (
<div className={styles.note}>
{tx(
"Ruff formats with the indent, tab character and hard wrap set here, and Black with the hard wrap, when no Ruff or Black configuration of the project or user applies. A file's .editorconfig values come first, as in the editor.",
)}
</div>
)}
{lang.id === "php" && (
<section aria-label={tx("Alignment")}>
<div className={styles.previewTitle}>
+11
View File
@@ -29,6 +29,7 @@ const DocstringsPage = lazyPage("python.docstrings", () =>
import("../languages/DocstringsPage").then((m) => m.DocstringsPage),
);
const RuffPage = lazyPage("python.ruff", () => import("../languages/FormatterPage").then((m) => m.RuffPage));
const BlackPage = lazyPage("python.black", () => import("../languages/FormatterPage").then((m) => m.BlackPage));
const PhpPage = lazyPage("languages.php", () => import("../languages/LanguagePages").then((m) => m.PhpPage));
const RubyPage = lazyPage("languages.ruby", () => import("../languages/LanguagePages").then((m) => m.RubyPage));
const RustPage = lazyPage("languages.rust", () => import("../languages/LanguagePages").then((m) => m.RustPage));
@@ -247,6 +248,16 @@ export const LANGUAGE_PAGES: PageSpec[] = [
],
component: RuffPage,
},
{
id: "python.black",
projectScope: true,
defaultScope: "project",
title: "Black formatter",
group: LANGUAGES_GROUP,
order: 403.4,
keywords: ["formatter", "black", "python", "pyproject.toml", "tool.black", "format on save"],
component: BlackPage,
},
{
id: "languages.php",
projectScope: true,
+7 -4
View File
@@ -26,7 +26,7 @@ const DEFAULT_GO_BUILD_TAGS: GoBuildTags = {
experiments: "",
};
/** An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. */
/** An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats. */
interface ExternalFormatterValid {
path: string;
configurationDirectory: string;
@@ -64,7 +64,7 @@ const DEFAULT_BIOME_FORMATTER: ExternalFormatterValid = {
languages: ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"],
};
const DEFAULT_RUFF_FORMATTER: ExternalFormatterValid = {
const DEFAULT_PYTHON_FORMATTER: ExternalFormatterValid = {
...DEFAULT_FORMATTER,
languages: ["python"],
};
@@ -211,6 +211,7 @@ export interface LanguagesValid {
oxfmt: ExternalFormatterValid;
biome: ExternalFormatterValid;
ruff: ExternalFormatterValid;
black: ExternalFormatterValid;
java: {
jdk: string;
languageLevel: (typeof JAVA_LANGUAGE_LEVELS)[number];
@@ -323,7 +324,8 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
prettier: DEFAULT_FORMATTER,
oxfmt: DEFAULT_FORMATTER,
biome: DEFAULT_BIOME_FORMATTER,
ruff: DEFAULT_RUFF_FORMATTER,
ruff: DEFAULT_PYTHON_FORMATTER,
black: DEFAULT_PYTHON_FORMATTER,
java: {
jdk: "",
languageLevel: "",
@@ -501,7 +503,8 @@ export function validateLanguages(raw: unknown): LanguagesValid {
prettier: validateFormatter(l.prettier),
oxfmt: validateFormatter(l.oxfmt),
biome: validateFormatter(l.biome, DEFAULT_BIOME_FORMATTER),
ruff: validateFormatter(l.ruff, DEFAULT_RUFF_FORMATTER),
ruff: validateFormatter(l.ruff, DEFAULT_PYTHON_FORMATTER),
black: validateFormatter(l.black, DEFAULT_PYTHON_FORMATTER),
java: {
jdk: text(java.jdk, d.java.jdk),
languageLevel: oneOf(java.languageLevel, JAVA_LANGUAGE_LEVELS, d.java.languageLevel),
+12
View File
@@ -3763,6 +3763,18 @@
"Pipenv Environment": "Pipenv Environment",
"Install packages from Pipfile": "Install packages from Pipfile",
"Runs “pipenv --python <base>” in the project, which writes a Pipfile (from requirements.txt if there is one) when the project has none. Pipenv chooses where to store the environment and reuses an existing one.": "Runs “pipenv --python <base>” in the project, which writes a Pipfile (from requirements.txt if there is one) when the project has none. Pipenv chooses where to store the environment and reuses an existing one.",
"Black formatter": "Black formatter",
"Reformat with Black": "Reformat with Black",
"Black formatting failed": "Black formatting failed",
"Black formatting timed out": "Black formatting timed out",
"Black path": "Black path",
"Auto: the project interpreter's environment, managed installation, then PATH. An explicit path overrides auto detection.": "Auto: the project interpreter's environment, managed installation, then PATH. An explicit path overrides auto detection.",
"Black formats Python instead of Ruff below a pyproject.toml with [tool.black], or when it is the selected provider.": "Black formats Python instead of Ruff below a pyproject.toml with [tool.black], or when it is the selected provider.",
"Run Black on save for enabled languages when it is the selected formatting provider. Reformat code in Actions on Save also runs it.": "Run Black on save for enabled languages when it is the selected formatting provider. Reformat code in Actions on Save also runs it.",
"Automatic (projects with [tool.black])": "Automatic (projects with [tool.black])",
"{name} left the file unchanged: its configuration excludes it": "{name} left the file unchanged: its configuration excludes it",
"This Black cannot format a selection (Black 23.11 or later can); formatted the whole file": "This Black cannot format a selection (Black 23.11 or later can); formatted the whole file",
"Ruff formats with the indent, tab character and hard wrap set here, and Black with the hard wrap, when no Ruff or Black configuration of the project or user applies. A file's .editorconfig values come first, as in the editor.": "Ruff formats with the indent, tab character and hard wrap set here, and Black with the hard wrap, when no Ruff or Black configuration of the project or user applies. A file's .editorconfig values come first, as in the editor.",
"Latest": "Latest",
"Checking for newer versions": "Checking for newer versions",
"Could not check for newer versions of the packages.": "Could not check for newer versions of the packages.",
+12
View File
@@ -9998,6 +9998,18 @@
"Pipenv Environment": "Pipenv 环境",
"Install packages from Pipfile": "安装 Pipfile 中的软件包",
"Runs “pipenv --python <base>” in the project, which writes a Pipfile (from requirements.txt if there is one) when the project has none. Pipenv chooses where to store the environment and reuses an existing one.": "在项目中运行“pipenv --python <base>”。项目没有 Pipfile 时会写入一个(有 requirements.txt 时从中导入)。环境的存放位置由 Pipenv 决定,已有环境会被复用。",
"Black formatter": "Black 格式化工具",
"Reformat with Black": "使用 Black 重新格式化",
"Black formatting failed": "Black 格式化失败",
"Black formatting timed out": "Black 格式化超时",
"Black path": "Black 路径",
"Auto: the project interpreter's environment, managed installation, then PATH. An explicit path overrides auto detection.": "自动:依次查找项目解释器的环境、托管安装和 PATH。明确指定的路径优先于自动检测。",
"Black formats Python instead of Ruff below a pyproject.toml with [tool.black], or when it is the selected provider.": "在含 [tool.black] 的 pyproject.toml 所在目录及其子目录中,或选择 Black 作为格式化工具时,Black 将代替 Ruff 格式化 Python。",
"Run Black on save for enabled languages when it is the selected formatting provider. Reformat code in Actions on Save also runs it.": "对已启用的语言,在选择 Black 作为格式化工具时于保存时运行。保存时操作中的“重新格式化代码”也会运行它。",
"Automatic (projects with [tool.black])": "自动(含 [tool.black] 的项目)",
"{name} left the file unchanged: its configuration excludes it": "{name} 未修改文件:它的配置排除了此文件",
"This Black cannot format a selection (Black 23.11 or later can); formatted the whole file": "此版本的 Black 不能格式化选区(Black 23.11 及以上版本可以),已格式化整个文件",
"Ruff formats with the indent, tab character and hard wrap set here, and Black with the hard wrap, when no Ruff or Black configuration of the project or user applies. A file's .editorconfig values come first, as in the editor.": "项目和用户都没有 Ruff 或 Black 配置时,Ruff 按这里设置的缩进、制表符和硬换行格式化,Black 按这里的硬换行格式化。与编辑器一样,文件的 .editorconfig 设置优先。",
"Latest": "最新版本",
"Checking for newer versions": "正在检查新版本",
"Could not check for newer versions of the packages.": "无法检查软件包的新版本。",