diff --git a/pylsp/hookspecs.py b/pylsp/hookspecs.py index cf97c745..98fef3b0 100644 --- a/pylsp/hookspecs.py +++ b/pylsp/hookspecs.py @@ -120,6 +120,11 @@ def pylsp_references( pass +@hookspec(firstresult=True) +def pylsp_prepare_rename(config, workspace, document, position) -> None: + pass + + @hookspec(firstresult=True) def pylsp_rename(config, workspace, document, position, new_name) -> None: pass diff --git a/pylsp/plugins/jedi_rename.py b/pylsp/plugins/jedi_rename.py index b35e321a..636fbeef 100644 --- a/pylsp/plugins/jedi_rename.py +++ b/pylsp/plugins/jedi_rename.py @@ -8,12 +8,44 @@ log = logging.getLogger(__name__) +def _rename_location(document, position): + # LSP columns count UTF-16 code units, whereas Jedi indexes Python strings. + line_number = position["line"] + lines = document.lines + line = lines[line_number].rstrip("\r\n") if 0 <= line_number < len(lines) else "" + prefix = line.encode("utf-16-le")[: 2 * position["character"]] + column = len(prefix.decode("utf-16-le", errors="ignore")) + return line, {"line": line_number + 1, "column": column} + + +@hookimpl +def pylsp_prepare_rename(document, position): + line, cursor = _rename_location(document, position) + if not line: + return None + references = document.jedi_script().get_references( + **cursor, include_builtins=False, scope="file" + ) + for reference in references: + if reference.line != cursor["line"] or reference.column is None: + continue + start = reference.column + if start <= cursor["column"] <= start + len(reference.name): + first = len(line[:start].encode("utf-16-le")) // 2 + last = first + len(reference.name.encode("utf-16-le")) // 2 + return { + "start": {"line": position["line"], "character": first}, + "end": {"line": position["line"], "character": last}, + } + return None + + @hookimpl def pylsp_rename(config, workspace, document, position, new_name): log.debug( "Executing rename of %s to %s", document.word_at_position(position), new_name ) - kwargs = _utils.position_to_jedi_linecolumn(document, position) + _, kwargs = _rename_location(document, position) kwargs["new_name"] = new_name try: refactoring = document.jedi_script().rename(**kwargs) diff --git a/pylsp/python_lsp.py b/pylsp/python_lsp.py index bdc072d4..cbc0b857 100644 --- a/pylsp/python_lsp.py +++ b/pylsp/python_lsp.py @@ -275,6 +275,24 @@ def _hook(self, hook_name, doc_uri=None, **kwargs): config=self.config, workspace=workspace, document=doc, **kwargs ) + def _can_prepare_rename(self): + rename_capabilities = self.config.capabilities.get("textDocument", {}).get( + "rename", {} + ) + if not rename_capabilities.get("prepareSupport"): + return False + + # Clients choose their rename workflow at initialization, but users can + # switch rename providers later with workspace/didChangeConfiguration. + hooks = self.config.plugin_manager.hook + renamers = hooks.pylsp_rename.get_hookimpls() + preparers = { + impl.plugin_name for impl in hooks.pylsp_prepare_rename.get_hookimpls() + } + return all(impl.plugin_name in preparers for impl in renamers) and any( + impl.plugin not in self.config.disabled_plugins for impl in renamers + ) + def capabilities(self): server_capabilities = { "codeActionProvider": True, @@ -296,7 +314,9 @@ def capabilities(self): }, "hoverProvider": True, "referencesProvider": True, - "renameProvider": True, + "renameProvider": {"prepareProvider": True} + if self._can_prepare_rename() + else True, "foldingRangeProvider": True, "signatureHelpProvider": {"triggerCharacters": ["(", ",", "="]}, "textDocumentSync": { @@ -551,6 +571,9 @@ def references(self, doc_uri, position, exclude_declaration): ) ) + def prepare_rename(self, doc_uri, position): + return self._hook("pylsp_prepare_rename", doc_uri, position=position) + def rename(self, doc_uri, position, new_name): return self._hook("pylsp_rename", doc_uri, position=position, new_name=new_name) @@ -805,6 +828,11 @@ def m_text_document__document_symbol(self, textDocument=None, **_kwargs): def m_text_document__formatting(self, textDocument=None, options=None, **_kwargs): return self.format_document(textDocument["uri"], options) + def m_text_document__prepare_rename( + self, textDocument=None, position=None, **_kwargs + ): + return self.prepare_rename(textDocument["uri"], position) + def m_text_document__rename( self, textDocument=None, position=None, newName=None, **_kwargs ): diff --git a/test/plugins/test_jedi_rename.py b/test/plugins/test_jedi_rename.py index 349274be..d0c25aab 100644 --- a/test/plugins/test_jedi_rename.py +++ b/test/plugins/test_jedi_rename.py @@ -5,7 +5,7 @@ import pytest -from pylsp import uris +from pylsp import hookimpl, uris from pylsp.plugins.jedi_rename import pylsp_rename from pylsp.workspace import Document @@ -33,6 +33,56 @@ def tmp_workspace(temp_workspace_factory): ) +def test_prepare_rename_capability(pylsp) -> None: + assert pylsp.capabilities()["renameProvider"] is True + pylsp.config.capabilities["textDocument"] = {"rename": {"prepareSupport": True}} + assert pylsp.capabilities()["renameProvider"] == {"prepareProvider": True} + + pylsp.config.update({"plugins": {"jedi_rename": {"enabled": False}}}) + assert pylsp.capabilities()["renameProvider"] is True + + +def test_prepare_rename_with_legacy_plugin(pylsp) -> None: + class RenamePlugin: + @hookimpl + def pylsp_rename(self): + return {"changes": {}} + + pylsp.config.plugin_manager.register(RenamePlugin(), name="legacy_rename") + pylsp.config.capabilities["textDocument"] = {"rename": {"prepareSupport": True}} + assert pylsp.capabilities()["renameProvider"] is True + + pylsp.config.update({"plugins": {"jedi_rename": {"enabled": False}}}) + uri = uris.from_fs_path(os.path.join(pylsp.workspace.root_path, DOC_NAME_SIMPLE)) + result = pylsp.m_text_document__rename( + {"uri": uri}, {"line": 0, "character": 0}, "new_name" + ) + assert result == {"changes": {}} + + +def test_prepare_rename_range(pylsp) -> None: + uri = uris.from_fs_path(os.path.join(pylsp.workspace.root_path, "example.py")) + source = 'x = 1\n"😀😀";x+11 # x\n' + pylsp.workspace.put_document(uri, source) + document = {"uri": uri} + position = {"line": 1, "character": 7} + + assert pylsp.m_text_document__prepare_rename(document, position) == { + "start": position, + "end": {"line": 1, "character": 8}, + } + for line, character in [(1, 3), (1, 15), (2, 0)]: + assert ( + pylsp.m_text_document__prepare_rename( + document, {"line": line, "character": character} + ) + is None + ) + + changes = pylsp.m_text_document__rename(document, position, "y")["documentChanges"] + assert changes[0]["edits"][0]["newText"] == 'y = 1\n"😀😀";y+11 # x\n' + + def test_jedi_rename(tmp_workspace, config) -> None: # rename the `Test1` class position = {"line": 0, "character": 6}