From f179c970ba5d7d2d0f1794a5489798ee1a87a2ca Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 16 Nov 2026 12:39:35 +0800 Subject: [PATCH] feat(python): Extract Method, Inline and Introduce Parameter through pylsp-rope (#3665) pylsp with pylsp-rope runs next to the Python type checker for refactorings only (features = code-action, code-action-kinds = refactor, every pylsp plugin off): Extract Method, Inline, Introduce Parameter and module-level Introduce Constant in Python files, with rope's "including similar statements" as the all-occurrences choice. pylsp-rope is a managed companion tool, not offered for install when missing; .ropeproject is in the default ignored names. Refs #901 --- crates/ide-core/src/ignored.rs | 4 ++- crates/ide-language/src/registry.rs | 17 +++++++++-- crates/ide-tools/src/lib.rs | 12 ++++++++ crates/ide-tools/src/registry.rs | 11 +++++++ crates/ide-tools/src/tests.rs | 1 + languages/python.toml | 33 +++++++++++++++++++++ src/bindings.ts | 6 ++++ src/editor/refactor/catalog.ts | 3 ++ src/editor/refactor/refactorThis.test.ts | 8 +++++ src/editor/refactor/serverIntroduce.test.ts | 4 +++ src/editor/refactor/serverIntroduce.ts | 2 +- src/features/tools/LanguageServersPage.tsx | 1 + src/features/tools/__tests__/tools.test.tsx | 17 +++++++++++ src/features/tools/backend.ts | 1 + src/features/tools/missing.ts | 4 +-- src/platform/ignoredNames.ts | 1 + 16 files changed, 119 insertions(+), 6 deletions(-) diff --git a/crates/ide-core/src/ignored.rs b/crates/ide-core/src/ignored.rs index efda11acf..b43423df3 100644 --- a/crates/ide-core/src/ignored.rs +++ b/crates/ide-core/src/ignored.rs @@ -14,7 +14,8 @@ pub fn inside_git_repo(dir: &Path) -> bool { dir.ancestors().any(|d| d.join(".git").exists() || d.join(".jj").exists()) } -/// IDEA's default list, plus `.jj` and the Windows shell files. +/// IDEA's default list, plus `.jj`, rope's `.ropeproject` (pylsp-rope creates it in the +/// project root) and the Windows shell files. pub const DEFAULT_IGNORED_NAMES: &[&str] = &[ "*.pyc", "*.pyo", @@ -25,6 +26,7 @@ pub const DEFAULT_IGNORED_NAMES: &[&str] = &[ ".git", ".hg", ".jj", + ".ropeproject", ".svn", "CVS", "__pycache__", diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index f304cac60..604a78a16 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -679,7 +679,7 @@ mod tests { let got: Vec<(&str, bool)> = cfg .language_servers .iter() - .filter(|s| !s.require_root_marker) + .filter(|s| !s.require_root_marker && s.features.is_empty()) .map(|s| (s.name.as_str(), s.fallback)) .collect(); let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect(); @@ -779,13 +779,26 @@ mod tests { assert_eq!(served("lib/src/Parser.php"), None); } + #[test] + fn pylsp_adds_only_rope_refactorings_to_python() { + let reg = reg(); + let cfg = reg.get(&LanguageId::new("python")).unwrap(); + let pylsp = cfg.language_servers.iter().find(|s| s.name == "pylsp").unwrap(); + assert!(!pylsp.fallback && !pylsp.require_root_marker); + assert_eq!(pylsp.features, ["code-action"]); + assert_eq!(pylsp.code_action_kinds, ["refactor"]); + let plugins = pylsp.initialization_options.as_ref().unwrap()["pylsp"]["plugins"].as_table().unwrap(); + assert_eq!(plugins["jedi_completion"]["enabled"].as_bool(), Some(false)); + assert!(plugins.values().all(|p| p["enabled"].as_bool() == Some(false))); + } + #[test] fn ruff_serves_python_files_only_below_its_config() { let reg = reg(); let cfg = reg.get(&LanguageId::new("python")).unwrap(); let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect(); // After the fallbacks: hover, rename and symbols stay with the type checker. - assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff"]); + assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff", "pylsp"]); let ruff = cfg.language_servers.iter().find(|s| s.name == "ruff").unwrap(); assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", ["server".to_string()].as_slice())); assert!(ruff.require_root_marker && !ruff.fallback); diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index 9e64dcb5f..6804c6176 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -92,6 +92,10 @@ pub struct ToolInfo { /// The interchangeable servers this one belongs to, in preference order: a /// server and the `fallback` ones after it. Empty when it has none. pub alternatives: Vec, + /// A language server used for part of what its languages need (`features` in its + /// definition: pylsp-rope's refactorings next to basedpyright). Not offered for install + /// when missing; the Language Servers page lists it. + pub companion: bool, } /// Streamed install progress. @@ -331,6 +335,7 @@ struct Usage { args: Vec, initialization_options: Option, alternatives: Vec, + companion: bool, } fn usages(langs: &[LanguageConfig]) -> BTreeMap { @@ -364,6 +369,11 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap { add(name, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name); } } + for s in langs.iter().flat_map(|l| &l.language_servers).filter(|s| !s.features.is_empty()) { + if let Some(u) = map.get_mut(&s.name) { + u.companion = true; + } + } for (plugin, host) in registry::PLUGIN_HOSTS { let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default(); map.entry(plugin.to_string()).or_default().languages = languages; @@ -749,6 +759,7 @@ impl Tools { default_args: u.args.clone(), default_initialization_options: u.initialization_options.clone(), alternatives: u.alternatives.clone(), + companion: u.companion, }) .map(|info| self.apply_custom(info, None)); }; @@ -775,6 +786,7 @@ impl Tools { default_args: usage.map(|u| u.args.clone()).unwrap_or_default(), default_initialization_options: usage.and_then(|u| u.initialization_options.clone()), alternatives: usage.map(|u| u.alternatives.clone()).unwrap_or_default(), + companion: usage.is_some_and(|u| u.companion), }) .map(|info| self.apply_custom(info, Some(spec))) } diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 67f20c192..e3be6b46e 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -289,6 +289,17 @@ pub static TOOLS: &[ToolSpec] = &[ homepage: "https://docs.astral.sh/ty/", needs: &[], }, + ToolSpec { + name: "pylsp", + display: "pylsp-rope (Python refactorings)", + kind: LanguageServer, + commands: &["pylsp"], + method: Method::PipVenv { package: "pylsp-rope" }, + fallback: None, + version: ver("pylsp"), + homepage: "https://github.com/python-rope/pylsp-rope", + needs: &[], + }, ToolSpec { name: "pyrefly", display: "Pyrefly (Python)", diff --git a/crates/ide-tools/src/tests.rs b/crates/ide-tools/src/tests.rs index c67a2b040..ca5d49c0b 100644 --- a/crates/ide-tools/src/tests.rs +++ b/crates/ide-tools/src/tests.rs @@ -380,6 +380,7 @@ fn install_joined_after_it_finished_returns_the_result() { default_args: vec![], default_initialization_options: None, alternatives: vec![], + companion: false, }; release_install_slot("marksman", &slot); slot.finish(Ok(ok)); diff --git a/languages/python.toml b/languages/python.toml index b3f331a44..4a23fdf17 100644 --- a/languages/python.toml +++ b/languages/python.toml @@ -59,6 +59,39 @@ root-markers = ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"] require-root-marker = true install-hint = "pip install ruff (or: uv tool install ruff)" +# Refactorings only (Extract Method / Variable, Inline, Introduce Parameter) from rope, +# next to the type checker: pylsp's own completion, hover, linting and formatting +# stay off, and its other code actions (quick fixes on every line) are dropped. +[[language-servers]] +name = "pylsp" +command = "pylsp" +features = ["code-action"] +code-action-kinds = ["refactor"] +root-markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"] +install-hint = "pip install pylsp-rope (or: uv tool install python-lsp-server --with pylsp-rope)" + +[language-servers.initialization-options.pylsp.plugins] +autopep8 = { enabled = false } +flake8 = { enabled = false } +folding = { enabled = false } +jedi_completion = { enabled = false } +jedi_definition = { enabled = false } +jedi_highlight = { enabled = false } +jedi_hover = { enabled = false } +jedi_references = { enabled = false } +jedi_rename = { enabled = false } +jedi_signature_help = { enabled = false } +jedi_symbols = { enabled = false } +mccabe = { enabled = false } +preload = { enabled = false } +pycodestyle = { enabled = false } +pydocstyle = { enabled = false } +pyflakes = { enabled = false } +pylint = { enabled = false } +rope_autoimport = { enabled = false } +rope_completion = { enabled = false } +yapf = { enabled = false } + [debugger] adapter = "debugpy" command = "python3" diff --git a/src/bindings.ts b/src/bindings.ts index 6ba08d8dd..267b83691 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -10747,6 +10747,12 @@ export type ToolInfo = { * server and the `fallback` ones after it. Empty when it has none. */ alternatives: string[], + /** + * A language server used for part of what its languages need (`features` in its + * definition: pylsp-rope's refactorings next to basedpyright). Not offered for install + * when missing; the Language Servers page lists it. + */ + companion: boolean, }; export type ToolKind = "languageServer" | "debugger" | diff --git a/src/editor/refactor/catalog.ts b/src/editor/refactor/catalog.ts index c421f821b..52175cabf 100644 --- a/src/editor/refactor/catalog.ts +++ b/src/editor/refactor/catalog.ts @@ -146,6 +146,9 @@ export function classifyAction(action: Pick): Refa ) ) return null; + // rope: a module-level method has no IDEA counterpart; a module-level variable is a constant. + if (/\bglobal method\b/i.test(title)) return null; + if (/\bglobal variable\b/i.test(title)) return "extractConstant"; if (is(/function|method/i)) return "extractMethod"; if (is(/field|member|property/i)) return "extractField"; if (is(/parameter|argument/i)) return "extractParameter"; diff --git a/src/editor/refactor/refactorThis.test.ts b/src/editor/refactor/refactorThis.test.ts index 35ec6962a..995e45192 100644 --- a/src/editor/refactor/refactorThis.test.ts +++ b/src/editor/refactor/refactorThis.test.ts @@ -153,6 +153,14 @@ describe("catalog", () => { expect(c("Move to a new file", "refactor")).toBe("move"); expect(c("Inline variable", "refactor")).toBe("inline"); expect(c("Convert to template string", "refactor")).toBeNull(); + // pylsp-rope (Python). + expect(c("Extract method including similar statements", "refactor.extract")).toBe("extractMethod"); + expect(c("Extract global method", "refactor.extract")).toBeNull(); + expect(c("Extract variable", "refactor.extract")).toBe("extractVariable"); + expect(c("Extract global variable including similar statements", "refactor.extract")).toBe("extractConstant"); + expect(c("Inline method/variable/parameter", "refactor.inline")).toBe("inline"); + expect(c("Introduce parameter", "refactor")).toBe("extractParameter"); + expect(c("To method object", "refactor.rewrite")).toBeNull(); }); it("knows which kinds an advertised list can produce", () => { diff --git a/src/editor/refactor/serverIntroduce.test.ts b/src/editor/refactor/serverIntroduce.test.ts index 4eb3df4a9..d2187cb72 100644 --- a/src/editor/refactor/serverIntroduce.test.ts +++ b/src/editor/refactor/serverIntroduce.test.ts @@ -69,6 +69,10 @@ describe("occurrenceVariants", () => { expect(occurrenceVariants([one, all])).toEqual({ one, all }); expect(occurrenceVariants([one])).toBeNull(); expect(occurrenceVariants([one, action("Extract to field"), all])).toBeNull(); + // rope's "similar statements" are the other occurrences. + const rope = action("Extract variable"); + const similar = action("Extract variable including similar statements"); + expect(occurrenceVariants([similar, rope])).toEqual({ one: rope, all: similar }); }); }); diff --git a/src/editor/refactor/serverIntroduce.ts b/src/editor/refactor/serverIntroduce.ts index 09e3e7f52..ce01c6365 100644 --- a/src/editor/refactor/serverIntroduce.ts +++ b/src/editor/refactor/serverIntroduce.ts @@ -102,7 +102,7 @@ export async function chooseExpressionFirst(view: EditorView, then: () => unknow // --------------------------------------------------------------------------- // Occurrences chooser -const ALL_OCCURRENCES = /\b(all|every) (the )?occurrences?\b|\breplace all\b/i; +const ALL_OCCURRENCES = /\b(all|every) (the )?occurrences?\b|\breplace all\b|\bincluding similar statements\b/i; /** The single-occurrence / all-occurrences pair among a refactoring's actions, if the server offers both. */ export function occurrenceVariants(actions: readonly CodeAction[]): { one: CodeAction; all: CodeAction } | null { diff --git a/src/features/tools/LanguageServersPage.tsx b/src/features/tools/LanguageServersPage.tsx index b62395486..a37e31d46 100644 --- a/src/features/tools/LanguageServersPage.tsx +++ b/src/features/tools/LanguageServersPage.tsx @@ -128,6 +128,7 @@ function pendingTool(name: string, entry: ServerEntry, languages: string[]): Too defaultArgs: [], defaultInitializationOptions: null, alternatives: [], + companion: false, }; } diff --git a/src/features/tools/__tests__/tools.test.tsx b/src/features/tools/__tests__/tools.test.tsx index a2b506a7d..8e86fb99a 100644 --- a/src/features/tools/__tests__/tools.test.tsx +++ b/src/features/tools/__tests__/tools.test.tsx @@ -225,6 +225,7 @@ describe("missing language server prompt", () => { installMethod: "uv (virtualenv)", languages: ["Python"], alternatives: [], + companion: false, }); await promptInstall("ruff", true, new Set(), true); expect(notes.at(-1)).toMatchObject({ @@ -234,6 +235,22 @@ describe("missing language server prompt", () => { }); }); + it("doesn't offer a companion server (refactorings only) when it is missing", async () => { + const template = sampleTools()[0]!; + backend.tools.push({ + ...template, + name: "pylsp", + displayName: "pylsp-rope (Python refactorings)", + command: "pylsp", + status: "missing", + languages: ["Rope Only"], + alternatives: [], + companion: true, + }); + expect(await promptInstall("pylsp")).toBe(false); + expect(notes).toEqual([]); + }); + it("stays silent when an installed alternative serves the same languages", async () => { const off = installMissingServerPrompts(); // typescript-language-server (on PATH) covers vtsls' languages. diff --git a/src/features/tools/backend.ts b/src/features/tools/backend.ts index d7b6fd142..288f0e8d9 100644 --- a/src/features/tools/backend.ts +++ b/src/features/tools/backend.ts @@ -72,6 +72,7 @@ function tool(partial: Partial & Pick) defaultArgs: [], defaultInitializationOptions: null, alternatives: [], + companion: false, ...partial, }; } diff --git a/src/features/tools/missing.ts b/src/features/tools/missing.ts index 2cac4ced3..ded4e1793 100644 --- a/src/features/tools/missing.ts +++ b/src/features/tools/missing.ts @@ -15,7 +15,7 @@ export const missingKey = (name: string) => `lsp-missing-${name}`; /** * `offered`: servers already offered for install. A fallback of one of them (pyright * after basedpyright) stays quiet: installing the first is enough, and the Language - * Servers… page offers the others. + * Servers… page offers the others. So does a companion server (pylsp-rope's refactorings). */ export async function promptInstall( name: string, @@ -25,7 +25,7 @@ export async function promptInstall( ): Promise { if (!useTools.getState().loaded) await refreshTools(); const tool = toolByName(name); - if (!tool || !tool.canInstall || tool.status !== "missing") return false; + if (!tool || !tool.canInstall || tool.status !== "missing" || tool.companion) return false; const position = tool.alternatives.indexOf(name); if (position > 0 && tool.alternatives.slice(0, position).some((n) => offered.has(n))) return false; formatter ||= tool.kind === "formatter"; diff --git a/src/platform/ignoredNames.ts b/src/platform/ignoredNames.ts index 838297672..df7493883 100644 --- a/src/platform/ignoredNames.ts +++ b/src/platform/ignoredNames.ts @@ -12,6 +12,7 @@ export const DEFAULT_IGNORED_NAMES: readonly string[] = [ ".git", ".hg", ".jj", + ".ropeproject", ".svn", "CVS", "__pycache__",