简体   繁体   中英

How can I automatically trigger the rename flow after extracting into a variable (LSP)?

I'm implementing IDE support for a language using Language Server Protocol.

I want to trigger a rename after extracting a variable into the current scope. That is, I've implemented steps 1 to 2 of the current flow and want to know how to implement 3 and 4

  1. When the user selects an expression a yellow lightbulb shows up. Example: z = 3 + /*selection-start*/5000/*selection-end*/ 灯泡

  2. When the user selects "extract into variable" then a new variable called "placeholder" is created in the current scope and the original expression is assigned to it. Example: placeholder = 5000; z = 3 + placeholder placeholder = 5000; z = 3 + placeholder 重命名

  3. The first instance of placeholder is highlighted and the text box for renaming pops up. When the user types "the_new_name" and presses Return then the text is: the_new_name = 5000; z = 3 + the_new_name the_new_name = 5000; z = 3 + the_new_name

更名

Is it possible to implement this flow with LSP? If so, how? I checked the LSP spec and it sounds like I'm looking for a Command , but I didn't see a built-in Command for renaming

TypeScript's language server has the behavior I'm trying to replicate (implemented around here ), but TypeScript doesn't implement language server protocol, so peeking at its source didn't help me. The screenshots above are from the TypeScript plugin built into VSCode

It seems as if editors must call for this rename themselves. Servers can send a list of edits as a result of a code action request, however they cannot request input from the user at this time: https://github.com/microsoft/language-server-protocol/issues/1641

LSP does not support this flow, but it can be done with a custom command. Here's one technique:

  • Include snippet text in the the WorkspaceEdit s, like "${0: placeholder}". Snippet syntax is documented here .
  • In the client, when handling code action responses, detect snippet syntax in edits and then use the IDE's APIs for triggering the rename flow. For VSCode, this can be done by triggering a custom command that uses VSCode APIs. I couldn't find any documentation for this, so cargo-culted Rust-Analyzer's solution . (function command(editor: vscode.editor) {... editor.replace(range, text)... }`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM