org.eclipse.lsp4j.WorkspaceEdit Java Examples
The following examples show how to use
org.eclipse.lsp4j.WorkspaceEdit.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
public static WorkspaceEdit createWorkspaceEditForAddMXMLNamespace(String nsPrefix, String nsURI, String fileText, String fileURI, int startIndex, int endIndex) { TextEdit textEdit = createTextEditForAddMXMLNamespace(nsPrefix, nsURI, fileText, startIndex, endIndex); if (textEdit == null) { return null; } WorkspaceEdit workspaceEdit = new WorkspaceEdit(); HashMap<String,List<TextEdit>> changes = new HashMap<>(); List<TextEdit> edits = new ArrayList<>(); edits.add(textEdit); changes.put(fileURI, edits); workspaceEdit.setChanges(changes); return workspaceEdit; }
Example #2
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
public static WorkspaceEdit createWorkspaceEditForAddImport(IDefinition definition, String fileText, String uri, ImportRange importRange) { TextEdit textEdit = createTextEditForAddImport(definition.getQualifiedName(), fileText, importRange); if (textEdit == null) { return null; } WorkspaceEdit workspaceEdit = new WorkspaceEdit(); HashMap<String,List<TextEdit>> changes = new HashMap<>(); List<TextEdit> edits = new ArrayList<>(); edits.add(textEdit); changes.put(uri, edits); workspaceEdit.setChanges(changes); return workspaceEdit; }
Example #3
Source File: OrganizeImportsCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testOrganizeImportsUnused() throws CoreException, BadLocationException { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.ArrayList;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); WorkspaceEdit rootEdit = new WorkspaceEdit(); command.organizeImportsInCompilationUnit(cu, rootEdit); assertEquals(buf.toString(), getOrganizeImportResult(cu, rootEdit)); }
Example #4
Source File: SourceAssistProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private Optional<Either<Command, CodeAction>> convertToWorkspaceEditAction(CodeActionContext context, ICompilationUnit cu, String name, String kind, TextEdit edit) { WorkspaceEdit workspaceEdit = convertToWorkspaceEdit(cu, edit); if (!ChangeUtil.hasChanges(workspaceEdit)) { return Optional.empty(); } Command command = new Command(name, CodeActionHandler.COMMAND_ID_APPLY_EDIT, Collections.singletonList(workspaceEdit)); if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(kind)) { CodeAction codeAction = new CodeAction(name); codeAction.setKind(kind); codeAction.setCommand(command); codeAction.setDiagnostics(context.getDiagnostics()); return Optional.of(Either.forRight(codeAction)); } else { return Optional.of(Either.forLeft(command)); } }
Example #5
Source File: ChangeUtilTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testConvertSimpleCompositeChange() throws CoreException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null); CompositeChange change = new CompositeChange("simple composite change"); RenameCompilationUnitChange resourceChange = new RenameCompilationUnitChange(cu, "ENew.java"); change.add(resourceChange); CompilationUnitChange textChange = new CompilationUnitChange("insertText", cu); textChange.setEdit(new InsertEdit(0, "// some content")); change.add(textChange); WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change); assertEquals(edit.getDocumentChanges().size(), 2); assertTrue(edit.getDocumentChanges().get(0).getRight() instanceof RenameFile); assertTrue(edit.getDocumentChanges().get(1).getLeft() instanceof TextDocumentEdit); }
Example #6
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
public static WorkspaceEdit createWorkspaceEditForRemoveUnusedImport(String fileText, String uri, Range range) { TextEdit textEdit = createTextEditForRemoveUnusedImport(fileText, range); if (textEdit == null) { return null; } WorkspaceEdit workspaceEdit = new WorkspaceEdit(); HashMap<String,List<TextEdit>> changes = new HashMap<>(); List<TextEdit> edits = new ArrayList<>(); edits.add(textEdit); changes.put(uri, edits); workspaceEdit.setChanges(changes); return workspaceEdit; }
Example #7
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
public static WorkspaceEdit createWorkspaceEditForGenerateLocalVariable( IIdentifierNode identifierNode, String uri, String text) { TextEdit textEdit = createTextEditForGenerateLocalVariable(identifierNode, text); if (textEdit == null) { return null; } WorkspaceEdit workspaceEdit = new WorkspaceEdit(); HashMap<String,List<TextEdit>> changes = new HashMap<>(); List<TextEdit> edits = new ArrayList<>(); edits.add(textEdit); changes.put(uri, edits); workspaceEdit.setChanges(changes); return workspaceEdit; }
Example #8
Source File: OrganizeImportsCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testGenericOrganizeImportsCall() throws Exception { importProjects("eclipse/hello"); IProject project = WorkspaceHelper.getProject("hello"); String filename = project.getFile("src/java/Foo4.java").getRawLocationURI().toString(); OrganizeImportsCommand command = new OrganizeImportsCommand(); Object result = command.organizeImports(Arrays.asList(filename)); assertNotNull(result); assertTrue(result instanceof WorkspaceEdit); WorkspaceEdit ws = (WorkspaceEdit) result; assertFalse(ws.getChanges().isEmpty()); TextEdit edit = ws.getChanges().values().stream().findFirst().get().get(0); assertEquals(0, edit.getRange().getStart().getLine()); assertEquals(4, edit.getRange().getEnd().getLine()); }
Example #9
Source File: CodeActionFactory.java From lemminx with Eclipse Public License 2.0 | 6 votes |
public static CodeAction replaceAt(String title, String replaceText, TextDocumentItem document, Diagnostic diagnostic, Collection<Range> ranges) { CodeAction insertContentAction = new CodeAction(title); insertContentAction.setKind(CodeActionKind.QuickFix); insertContentAction.setDiagnostics(Arrays.asList(diagnostic)); VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier( document.getUri(), document.getVersion()); List<TextEdit> edits = new ArrayList<TextEdit>(); for (Range range : ranges) { TextEdit edit = new TextEdit(range, replaceText); edits.add(edit); } TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, edits); WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit))); insertContentAction.setEdit(workspaceEdit); return insertContentAction; }
Example #10
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
public static WorkspaceEdit createWorkspaceEditForGenerateGetterAndSetter( IVariableNode variableNode, String uri, String text, boolean generateGetter, boolean generateSetter) { TextEdit textEdit = createTextEditForGenerateGetterAndSetter(variableNode, text, generateGetter, generateSetter); if (textEdit == null) { return null; } WorkspaceEdit workspaceEdit = new WorkspaceEdit(); HashMap<String,List<TextEdit>> changes = new HashMap<>(); List<TextEdit> edits = new ArrayList<>(); edits.add(textEdit); changes.put(uri, edits); workspaceEdit.setChanges(changes); return workspaceEdit; }
Example #11
Source File: CodeActionAcceptor.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** Adds a quick-fix code action with the given title, edit and command */ public void acceptQuickfixCodeAction(QuickfixContext context, String title, WorkspaceEdit edit, Command command) { if (edit == null && command == null) { return; } CodeAction codeAction = new CodeAction(); codeAction.setTitle(title); codeAction.setEdit(edit); codeAction.setCommand(command); codeAction.setKind(CodeActionKind.QuickFix); if (context.options != null && context.options.getCodeActionParams() != null) { CodeActionContext cac = context.options.getCodeActionParams().getContext(); if (cac != null && cac.getDiagnostics() != null) { codeAction.setDiagnostics(cac.getDiagnostics()); } } codeActions.add(Either.forRight(codeAction)); }
Example #12
Source File: CodeActionsUtils.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
private static void createCodeActionsForGenerateGetterAndSetter(IVariableNode variableNode, String uri, String fileText, Range codeActionsRange, List<Either<Command, CodeAction>> codeActions) { WorkspaceEdit getSetEdit = createWorkspaceEditForGenerateGetterAndSetter( variableNode, uri, fileText, true, true); CodeAction getAndSetCodeAction = new CodeAction(); getAndSetCodeAction.setTitle("Generate 'get' and 'set' accessors"); getAndSetCodeAction.setEdit(getSetEdit); getAndSetCodeAction.setKind(CodeActionKind.RefactorRewrite); codeActions.add(Either.forRight(getAndSetCodeAction)); WorkspaceEdit getterEdit = createWorkspaceEditForGenerateGetterAndSetter( variableNode, uri, fileText, true, false); CodeAction getterCodeAction = new CodeAction(); getterCodeAction.setTitle("Generate 'get' accessor (make read-only)"); getterCodeAction.setEdit(getterEdit); getterCodeAction.setKind(CodeActionKind.RefactorRewrite); codeActions.add(Either.forRight(getterCodeAction)); WorkspaceEdit setterEdit = createWorkspaceEditForGenerateGetterAndSetter( variableNode, uri, fileText, false, true); CodeAction setterCodeAction = new CodeAction(); setterCodeAction.setTitle("Generate 'set' accessor (make write-only)"); setterCodeAction.setEdit(setterEdit); setterCodeAction.setKind(CodeActionKind.RefactorRewrite); codeActions.add(Either.forRight(setterCodeAction)); }
Example #13
Source File: SaveActionHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private List<TextEdit> handleSaveActionOrganizeImports(String documentUri, IProgressMonitor monitor) { String uri = ResourceUtils.fixURI(JDTUtils.toURI(documentUri)); if (monitor.isCanceled()) { return Collections.emptyList(); } WorkspaceEdit organizedResult = organizeImportsCommand.organizeImportsInFile(uri); List<TextEdit> edit = organizedResult.getChanges().get(uri); edit = edit == null ? Collections.emptyList() : edit; return edit; }
Example #14
Source File: JDTLanguageServer.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Override public CompletableFuture<WorkspaceEdit> didRenameFiles(FileRenameParams params) { logInfo(">> document/didRenameFiles"); return computeAsyncWithClientProgress((monitor) -> { waitForLifecycleJobs(monitor); return FileEventHandler.handleRenameFiles(params, monitor); }); }
Example #15
Source File: RenameHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testRenameSuperMethod() throws JavaModelException, BadLocationException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); String[] codes = { "package test1;\n", "class A {\n", " public void bar() {\n", " }\n", "}\n", "class B extends A {\n", " public void bar() {\n", " super|*.bar();\n", " }\n", "}\n" }; StringBuilder builder = new StringBuilder(); Position pos = mergeCode(builder, codes); ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null); WorkspaceEdit edit = getRenameEdit(cu, pos, "TypeA"); assertNotNull(edit); assertEquals(1, edit.getChanges().size()); assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))), "package test1;\n" + "class TypeA {\n" + " public void bar() {\n" + " }\n" + "}\n" + "class B extends TypeA {\n" + " public void bar() {\n" + " super.bar();\n" + " }\n" + "}\n" ); }
Example #16
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static void convertCompositeChange(CompositeChange change, WorkspaceEdit edit) throws CoreException { Change[] changes = change.getChildren(); for (Change ch : changes) { if (ch instanceof CompositeChange) { convertCompositeChange((CompositeChange) ch, edit); } else { convertSingleChange(ch, edit); } } }
Example #17
Source File: ExtractFieldTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
protected boolean helper(ICompilationUnit cu, InitializeScope initializeIn, String expected) throws Exception { CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null); IProblem[] problems = astRoot.getProblems(); Range range = getRange(cu, problems); int start = DiagnosticsHelper.getStartOffset(cu, range); int end = DiagnosticsHelper.getEndOffset(cu, range); ExtractFieldRefactoring refactoring = new ExtractFieldRefactoring(astRoot, start, end - start); refactoring.setFieldName(refactoring.guessFieldName()); RefactoringStatus activationResult = refactoring.checkInitialConditions(new NullProgressMonitor()); assertTrue("activation was supposed to be successful", activationResult.isOK()); if (initializeIn != null) { if (initializeIn == InitializeScope.CURRENT_METHOD && !refactoring.canEnableSettingDeclareInMethod()) { return false; } else if (initializeIn == InitializeScope.CLASS_CONSTRUCTORS && !refactoring.canEnableSettingDeclareInConstructors()) { return false; } else if (initializeIn == InitializeScope.FIELD_DECLARATION && !refactoring.canEnableSettingDeclareInFieldDeclaration()) { return false; } refactoring.setInitializeIn(initializeIn.ordinal()); } RefactoringStatus checkInputResult = refactoring.checkFinalConditions(new NullProgressMonitor()); assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK()); Change change = refactoring.createChange(new NullProgressMonitor()); WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change); assertNotNull(change); String actual = evaluateChanges(edit.getChanges()); assertEquals(expected, actual); return true; }
Example #18
Source File: HashCodeEqualsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static WorkspaceEdit generateHashCodeEquals(GenerateHashCodeEqualsParams params) { IType type = SourceAssistProcessor.getSelectionType(params.context); Preferences preferences = JavaLanguageServerPlugin.getPreferencesManager().getPreferences(); boolean useJava7Objects = preferences.isHashCodeEqualsTemplateUseJava7Objects(); boolean useInstanceof = preferences.isHashCodeEqualsTemplateUseInstanceof(); boolean useBlocks = preferences.isCodeGenerationTemplateUseBlocks(); boolean generateComments = preferences.isCodeGenerationTemplateGenerateComments(); TextEdit edit = generateHashCodeEqualsTextEdit(type, params.fields, params.regenerate, useJava7Objects, useInstanceof, useBlocks, generateComments); return (edit == null) ? null : SourceAssistProcessor.convertToWorkspaceEdit(type.getCompilationUnit(), edit); }
Example #19
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static void convertSingleChange(Change change, WorkspaceEdit edit) throws CoreException { if (change instanceof CompositeChange) { return; } if (change instanceof TextChange) { convertTextChange((TextChange) change, edit); } else if (change instanceof ResourceChange) { convertResourceChange((ResourceChange) change, edit); } }
Example #20
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static void convertTextChange(TextChange textChange, WorkspaceEdit rootEdit) { Object modifiedElement = textChange.getModifiedElement(); if (!(modifiedElement instanceof IJavaElement)) { return; } TextEdit textEdits = textChange.getEdit(); if (textEdits == null) { return; } ICompilationUnit compilationUnit = (ICompilationUnit) ((IJavaElement) modifiedElement).getAncestor(IJavaElement.COMPILATION_UNIT); convertTextEdit(rootEdit, compilationUnit, textEdits); }
Example #21
Source File: GenerateAccessorsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static WorkspaceEdit generateAccessors(GenerateAccessorsParams params) { IType type = SourceAssistProcessor.getSelectionType(params.context); if (type == null || type.getCompilationUnit() == null) { return null; } Preferences preferences = JavaLanguageServerPlugin.getPreferencesManager().getPreferences(); TextEdit edit = generateAccessors(type, params.accessors, preferences.isCodeGenerationTemplateGenerateComments()); return (edit == null) ? null : SourceAssistProcessor.convertToWorkspaceEdit(type.getCompilationUnit(), edit); }
Example #22
Source File: RenameHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testRenameMethod() throws JavaModelException, BadLocationException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); String[] codes = { "package test1;\n", "public class E {\n", " public int bar() {\n", " }\n", " public int foo() {\n", " this.bar|*();\n", " }\n", "}\n" }; StringBuilder builder = new StringBuilder(); Position pos = mergeCode(builder, codes); ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null); WorkspaceEdit edit = getRenameEdit(cu, pos, "newname"); assertNotNull(edit); assertEquals(edit.getChanges().size(), 1); assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))), "package test1;\n" + "public class E {\n" + " public int newname() {\n" + " }\n" + " public int foo() {\n" + " this.newname();\n" + " }\n" + "}\n" ); }
Example #23
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static void convertCreateCompilationUnitChange(WorkspaceEdit edit, CreateCompilationUnitChange change) { ICompilationUnit unit = change.getCu(); CreateFile createFile = new CreateFile(); createFile.setUri(JDTUtils.toURI(unit)); createFile.setOptions(new CreateFileOptions(false, true)); edit.getDocumentChanges().add(Either.forRight(createFile)); InsertEdit textEdit = new InsertEdit(0, change.getPreview()); convertTextEdit(edit, unit, textEdit); }
Example #24
Source File: RenameHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testRenameJavadoc() throws JavaModelException, BadLocationException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); String[] codes = { "package test1;\n", "public class E {\n", " /**\n", " *@param i int\n", " */\n", " public int foo(int i|*) {\n", " E e = new E();\n", " e.foo();\n", " }\n", "}\n" }; StringBuilder builder = new StringBuilder(); Position pos = mergeCode(builder, codes); ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null); WorkspaceEdit edit = getRenameEdit(cu, pos, "i2"); assertNotNull(edit); assertEquals(edit.getChanges().size(), 1); assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))), "package test1;\n" + "public class E {\n" + " /**\n" + " *@param i2 int\n" + " */\n" + " public int foo(int i2) {\n" + " E e = new E();\n" + " e.foo();\n" + " }\n" + "}\n" ); }
Example #25
Source File: OrganizeImportsCommand.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public void organizeImportsInPackageFragment(IPackageFragment fragment, WorkspaceEdit rootEdit) throws CoreException { HashSet<IJavaElement> result = new HashSet<>(); collectCompilationUnits(fragment.getParent(), result, fragment.getElementName()); for (IJavaElement elem : result) { if (elem.getElementType() == IJavaElement.COMPILATION_UNIT) { organizeImportsInCompilationUnit((ICompilationUnit) elem, rootEdit); } } }
Example #26
Source File: OrganizeImportsCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private String getOrganizeImportResult(ICompilationUnit cu, WorkspaceEdit we) throws BadLocationException, CoreException { List<TextEdit> change = we.getChanges().get(JDTUtils.toURI(cu)); if (change == null) { return cu.getSource(); } Document doc = new Document(); doc.set(cu.getSource()); return TextEditUtil.apply(doc, change); }
Example #27
Source File: RenameHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testRenameParameter() throws JavaModelException, BadLocationException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); String[] codes = { "package test1;\n", "public class E {\n", " public int foo(String str) {\n", " str|*.length();\n", " }\n", " public int bar(String str) {\n", " str.length();\n", " }\n", "}\n" }; StringBuilder builder = new StringBuilder(); Position pos = mergeCode(builder, codes); ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null); WorkspaceEdit edit = getRenameEdit(cu, pos, "newname"); assertNotNull(edit); assertEquals(edit.getChanges().size(), 1); assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))), "package test1;\n" + "public class E {\n" + " public int foo(String newname) {\n" + " newname.length();\n" + " }\n" + " public int bar(String str) {\n" + " str.length();\n" + " }\n" + "}\n"); }
Example #28
Source File: OrganizeImportsCommand.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
/** * Organize imports when select a project. * * @param proj * the target project * @return */ public WorkspaceEdit organizeImportsInProject(IProject proj) { WorkspaceEdit rootEdit = new WorkspaceEdit(); HashSet<IJavaElement> result = new HashSet<>(); collectCompilationUnits(JavaCore.create(proj), result, null); for (IJavaElement elem : result) { if (elem.getElementType() == IJavaElement.COMPILATION_UNIT) { organizeImportsInCompilationUnit((ICompilationUnit) elem, rootEdit); } } return rootEdit; }
Example #29
Source File: OrganizeImportsCommand.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public Object organizeImports(List<Object> arguments) throws CoreException { WorkspaceEdit edit = new WorkspaceEdit(); if (arguments != null && !arguments.isEmpty() && arguments.get(0) instanceof String) { final String fileUri = (String) arguments.get(0); final IPath rootPath = ResourceUtils.filePathFromURI(fileUri); if (rootPath == null) { throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "URI is not found")); } final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = wsroot.getFileForLocation(rootPath); if (resource == null) { resource = wsroot.getContainerForLocation(rootPath); } if (resource != null) { final OrganizeImportsCommand command = new OrganizeImportsCommand(); int type = resource.getType(); switch (type) { case IResource.PROJECT: edit = command.organizeImportsInProject(resource.getAdapter(IProject.class)); break; case IResource.FOLDER: edit = command.organizeImportsInDirectory(fileUri, resource.getProject()); break; case IResource.FILE: edit = command.organizeImportsInFile(fileUri); break; default://This can only be IResource.ROOT. Which is not relevant to jdt.ls // do nothing allow to return the empty WorkspaceEdit. break; } } } return edit; }
Example #30
Source File: WorkspaceEditHandler.java From lsp4intellij with Apache License 2.0 | 5 votes |
public static void applyEdit(PsiElement elem, String newName, UsageInfo[] infos, RefactoringElementListener listener, List<VirtualFile> openedEditors) { Map<String, List<TextEdit>> edits = new HashMap<>(); if (elem instanceof LSPPsiElement) { LSPPsiElement lspElem = (LSPPsiElement) elem; if (Stream.of(infos).allMatch(info -> info.getElement() instanceof LSPPsiElement)) { Stream.of(infos).forEach(ui -> { Editor editor = FileUtils.editorFromVirtualFile(ui.getVirtualFile(), ui.getProject()); TextRange range = ui.getElement().getTextRange(); Range lspRange = new Range(DocumentUtils.offsetToLSPPos(editor, range.getStartOffset()), DocumentUtils.offsetToLSPPos(editor, range.getEndOffset())); TextEdit edit = new TextEdit(lspRange, newName); String uri = null; try { uri = FileUtils.sanitizeURI( new URL(ui.getVirtualFile().getUrl().replace(" ", FileUtils.SPACE_ENCODED)).toURI() .toString()); } catch (MalformedURLException | URISyntaxException e) { LOG.warn(e); } if (edits.keySet().contains(uri)) { edits.get(uri).add(edit); } else { List<TextEdit> textEdits = new ArrayList<>(); textEdits.add(edit); edits.put(uri, textEdits); } }); WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits); applyEdit(workspaceEdit, "Rename " + lspElem.getName() + " to " + newName, openedEditors); } } }