|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +import { commands, window, ExtensionContext, workspace, Position, Uri, TextDocument } from 'vscode'; |
| 4 | +import { LanguageClient, FormattingOptions } from 'vscode-languageclient'; |
| 5 | +import { Commands as javaCommands } from './commands'; |
| 6 | +import { GetRefactorEditRequest, RefactorWorkspaceEdit, RenamePosition } from './protocol'; |
| 7 | + |
| 8 | +export function registerCommands(languageClient: LanguageClient, context: ExtensionContext) { |
| 9 | + registerApplyRefactorCommand(languageClient, context); |
| 10 | +} |
| 11 | + |
| 12 | +function registerApplyRefactorCommand(languageClient: LanguageClient, context: ExtensionContext): void { |
| 13 | + context.subscriptions.push(commands.registerCommand(javaCommands.RENAME_COMMAND, async (position: RenamePosition) => { |
| 14 | + try { |
| 15 | + const uri: Uri = Uri.parse(position.uri); |
| 16 | + const document: TextDocument = await workspace.openTextDocument(uri); |
| 17 | + if (document == null) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + const renamePosition: Position = document.positionAt(position.offset); |
| 22 | + await commands.executeCommand('editor.action.rename', [ |
| 23 | + document.uri, |
| 24 | + renamePosition, |
| 25 | + ]); |
| 26 | + } catch (error) { |
| 27 | + // do nothing. |
| 28 | + } |
| 29 | + })); |
| 30 | + |
| 31 | + context.subscriptions.push(commands.registerCommand(javaCommands.APPLY_REFACTORING_COMMAND, async (command: string, params: any) => { |
| 32 | + if (command === 'extractVariable' |
| 33 | + || command === 'extractVariableAllOccurrence' |
| 34 | + || command === 'extractConstant' |
| 35 | + || command === 'extractMethod') { |
| 36 | + const currentEditor = window.activeTextEditor; |
| 37 | + if (!currentEditor || !currentEditor.options) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + const formattingOptions: FormattingOptions = { |
| 42 | + tabSize: <number> currentEditor.options.tabSize, |
| 43 | + insertSpaces: <boolean> currentEditor.options.insertSpaces, |
| 44 | + }; |
| 45 | + const result: RefactorWorkspaceEdit = await languageClient.sendRequest(GetRefactorEditRequest.type, { |
| 46 | + command, |
| 47 | + context: params, |
| 48 | + options: formattingOptions, |
| 49 | + }); |
| 50 | + |
| 51 | + if (!result || !result.edit) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + const edit = languageClient.protocol2CodeConverter.asWorkspaceEdit(result.edit); |
| 56 | + if (edit) { |
| 57 | + await workspace.applyEdit(edit); |
| 58 | + } |
| 59 | + |
| 60 | + if (result.command) { |
| 61 | + if (result.command.arguments) { |
| 62 | + await commands.executeCommand(result.command.command, ...result.command.arguments); |
| 63 | + } else { |
| 64 | + await commands.executeCommand(result.command.command); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + })); |
| 69 | +} |
0 commit comments