feat(java): pass the import-on-demand thresholds to jdtls (#6117)

Adds Settings > Code Style > Java > Imports with "Class count to use import
with '*'" and "Names count to use static import with '*'", passed to jdtls as
java.sources.organizeImports.starThreshold / staticStarThreshold.

Organize imports used to collapse imports into wildcards on jdtls's defaults
(99, but jdtls keeps the last value it was sent). The thresholds are now always
sent, defaulting to 5 and 3 when the code style leaves them unset; an explicit
value in the server's own settings still wins.

Fixes #6026

Co-authored-by: muutot <[email protected]>
Цей коміт міститься в:
Muuтаmuutot authored and GitHub committed 2026-11-27 05:13:37 +08:00
1 джерело 138209c627
коміт 3d1eaf71e4
9 files changed
+220 -1

No files matched your search

+10
Переглянути файл
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
+53
Переглянути файл
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
Some(settings)
}
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
/// A threshold the server configuration sets explicitly is kept.
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
json!({
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
})
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
@@ -84,6 +98,7 @@ pub fn configure_formatter(
});
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
@@ -300,6 +315,44 @@ mod tests {
}
}
#[test]
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let imports = |cfg: &LanguageServerConfig| {
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
};
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
class_count_to_use_import_with_star: Some(7),
names_count_to_use_static_import_with_star: Some(4),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
let mut cfg = config("jdtls");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
// A threshold set in the server configuration wins.
let mut cfg = config("jdtls");
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
let mut cfg = config("rust-analyzer");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
}
#[test]
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
let dir = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -114,6 +114,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
## Tabs
+24
Переглянути файл
@@ -9162,6 +9162,18 @@ export type LanguageCodeStyle_Deserialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
@@ -9192,6 +9204,18 @@ export type LanguageCodeStyle_Serialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
+66
Переглянути файл
@@ -0,0 +1,66 @@
import { useMemo, type ComponentType } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings, stagedValue, useSettingsDialog } from "../model/staging";
import { codeStyleLanguagePages } from "../pages/editor/codeStyle";
const mocks = vi.hoisted(() => ({ languages: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
languages: mocks.languages,
},
};
});
beforeEach(() => {
mocks.languages.mockResolvedValue([
{ id: "java", name: "Java", indent: { tabSize: 4, insertSpaces: true } },
{ id: "rust", name: "Rust" },
]);
useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null });
openSettings("editor.codeStyle.java");
});
afterEach(cleanup);
function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) {
const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]);
return (
<PageContext.Provider value={value}>
<Page />
</PageContext.Provider>
);
}
async function page(language: string) {
const pages = await codeStyleLanguagePages();
const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!;
render(<CodeStylePage id={spec.id} Page={spec.component!} />);
}
const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages");
describe("Java Imports (IntelliSort)", () => {
it("stages the class-count and static-count options on the Java code style", async () => {
await page("java");
fireEvent.click(screen.getByRole("tab", { name: "Imports" }));
fireEvent.change(screen.getByLabelText("Class count to use import with *"), { target: { value: "7" } });
fireEvent.change(screen.getByLabelText("Names count to use static import with *"), { target: { value: "2" } });
expect(value()).toEqual({
java: { classCountToUseImportWithStar: 7, namesCountToUseStaticImportWithStar: 2 },
});
fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" }));
expect(value()).toEqual({});
});
it("keeps the Imports tab specific to Java", async () => {
await page("rust");
expect(screen.queryByRole("tab", { name: "Imports" })).toBeNull();
});
});
+48 -1
Переглянути файл
@@ -157,6 +157,11 @@ const COMMENTS = {
keywords: ["Line comment at first column", "Add a space at line comment start"],
};
const CASE = { id: "case", label: "Case", keywords: ["Keywords", "Identifiers", "To upper", "To lower"] };
const IMPORTS = {
id: "imports",
label: "Imports",
keywords: ["imports", "static imports", "wildcard", "class count", "import with *"],
};
const SPACES = { id: "spaces", label: "Spaces", keywords: ["Space", "Around binary operators", "Within braces"] };
const PUNCTUATION = { id: "punctuation", label: "Punctuation", keywords: ["Semicolons", "Quotes"] };
@@ -298,6 +303,41 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
),
});
}
if (lang.id === "java") {
tabs.push({
...IMPORTS,
content: (
<FormGroup>
<Row
label="Class count to use import with '*'"
hint="Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports)."
>
<NumberInput
value={own.classCountToUseImportWithStar ?? 5}
onChange={(n) => set({ classCountToUseImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Class count to use import with *"
/>
</Row>
<Row
label="Names count to use static import with '*'"
hint="Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports)."
>
<NumberInput
value={own.namesCountToUseStaticImportWithStar ?? 3}
onChange={(n) => set({ namesCountToUseStaticImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Names count to use static import with *"
/>
</Row>
</FormGroup>
),
});
}
if (TS_STYLE_LANGUAGES.has(lang.id)) {
tabs.push(
{
@@ -501,7 +541,14 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
...keywords,
]),
...(lang.id === "java"
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
? [
"Formatting profile",
"IntelliJ IDEA",
"Custom Eclipse formatter XML",
"Eclipse formatter XML",
IMPORTS.label,
...IMPORTS.keywords,
]
: []),
...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []),
...(lang.id === "sql" ? [CASE.label, ...CASE.keywords, "Do not change"] : []),
+4
Переглянути файл
@@ -47,6 +47,10 @@ export interface LanguageCodeStyle {
/** SQL › Case: Reformat Code's case for keywords and unquoted identifiers. */
keywordCase?: SqlWordCase;
identifierCase?: SqlWordCase;
/** Java: organize imports switches to a wildcard import once this many classes of one package are used (jdtls passthrough). */
classCountToUseImportWithStar?: number;
/** Java: organize imports switches to a wildcard static import once this many names are used (jdtls passthrough). */
namesCountToUseStaticImportWithStar?: number;
/** JavaScript / TypeScript › Punctuation (unset: tsserver's default, `ignore` / `auto`). */
semicolons?: "ignore" | "insert" | "remove";
quotes?: "auto" | "single" | "double";
+7
Переглянути файл
@@ -4118,6 +4118,13 @@
"Run '{command}' in '{rel}' to install them.": "Run '{command}' in '{rel}' to install them.",
"Run '{command}' to install them.": "Run '{command}' to install them.",
"Install Node.js Dependencies": "Install Node.js Dependencies",
"Imports": "Imports",
"Class count to use import with '*'": "Class count to use import with '*'",
"Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).",
"Class count to use import with *": "Class count to use import with *",
"Names count to use static import with '*'": "Names count to use static import with '*'",
"Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).",
"Names count to use static import with *": "Names count to use static import with *",
"Watch for changes": "Watch for changes",
"Rerun Automatically": "Rerun Automatically",
"Debug runs the tests once, without watching.": "Debug runs the tests once, without watching.",
+6
Переглянути файл
@@ -10564,6 +10564,12 @@
"Run with {title}": "使用 {title} 运行",
"Debug with {title}": "使用 {title} 调试",
"Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置",
"Class count to use import with '*'": "使用通配符导入的类数",
"Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "当同一个包使用达到该数量的类时使用通配符导入;默认为 5,999 表示始终保留单类导入。",
"Class count to use import with *": "使用通配符导入的类数",
"Names count to use static import with '*'": "使用通配符静态导入的名称数",
"Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "静态导入的名称达到该数量时使用通配符静态导入;默认为 3,999 表示始终保留单条导入。",
"Names count to use static import with *": "使用通配符静态导入的名称数",
"Watch for changes": "监视更改",
"Rerun Automatically": "自动重新运行",
"Debug runs the tests once, without watching.": "调试时测试只运行一次,不监视更改。",