private TextEdit change(final Position startPos, final Position endPos, final String newText) { TextEdit _textEdit = new TextEdit(); final Procedure1<TextEdit> _function = (TextEdit it) -> { if ((startPos != null)) { Range _range = new Range(); final Procedure1<Range> _function_1 = (Range it_1) -> { it_1.setStart(startPos); it_1.setEnd(endPos); }; Range _doubleArrow = ObjectExtensions.<Range>operator_doubleArrow(_range, _function_1); it.setRange(_doubleArrow); } it.setNewText(newText); }; return ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function); }
@Test public void testEquals() { Assert.assertEquals(new TextDocumentIdentifier("foo"), new TextDocumentIdentifier("foo")); Assert.assertNotEquals(new TextDocumentIdentifier("foo"), new TextDocumentIdentifier("bar")); CompletionItem e1 = new CompletionItem(); e1.setAdditionalTextEdits(new ArrayList<>()); e1.getAdditionalTextEdits().add(new TextEdit(new Range(new Position(1,1), new Position(1,1)), "foo")); CompletionItem e2 = new CompletionItem(); e2.setAdditionalTextEdits(new ArrayList<>()); e2.getAdditionalTextEdits().add(new TextEdit(new Range(new Position(1,1), new Position(1,1)), "foo")); CompletionItem e3 = new CompletionItem(); e3.setAdditionalTextEdits(new ArrayList<>()); e3.getAdditionalTextEdits().add(new TextEdit(new Range(new Position(1,1), new Position(1,2)), "foo")); Assert.assertEquals(e1, e2); Assert.assertNotEquals(e1, e3); Assert.assertEquals(e1.hashCode(), e2.hashCode()); Assert.assertNotEquals(e1.hashCode(), e3.hashCode()); }
@Test public void addImportToExisting() { String before = "package org.javacs;\n" + "\n" + "import java.util.List;\n" + "\n" + "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); String after = applyEdits(before, edits); assertThat( after, equalTo( "package org.javacs;\n" + "\n" + "import java.util.List;\n" + "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }")); }
@Test public void addImportAtBeginning() { String before = "package org.javacs;\n" + "\n" + "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "java.util", "List"); String after = applyEdits(before, edits); assertThat( after, equalTo( "package org.javacs;\n" + "\n" + "import java.util.List;\n" + "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }")); }
@Test public void importAlreadyExists() { String before = "package org.javacs;\n" + "\n" + "import java.util.List;\n" + "\n" + "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "java.util", "List"); String after = applyEdits(before, edits); assertThat( after, equalTo( "package org.javacs;\n" + "\n" + "import java.util.List;\n" + "\n" + "public class Example { void main() { } }")); }
private List<TextEdit> addImport(String content, String packageName, String className) { List<TextEdit> result = new ArrayList<>(); JavacHolder compiler = JavacHolder.create( Collections.singleton(Paths.get("src/test/test-project/workspace/src")), Collections.emptySet()); BiConsumer<JavacTask, CompilationUnitTree> doRefactor = (task, tree) -> { List<TextEdit> edits = new RefactorFile(task, tree).addImport(packageName, className); result.addAll(edits); }; compiler.compileBatch( Collections.singletonMap(FAKE_FILE, Optional.of(content)), doRefactor); return result; }
@Test public void testCompletion_import_package() throws JavaModelException{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "import java.sq \n" + "public class Foo {\n"+ " void foo() {\n"+ " }\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "java.sq"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); assertEquals(1, list.getItems().size()); CompletionItem item = list.getItems().get(0); // Check completion item assertNull(item.getInsertText()); assertEquals("java.sql",item.getLabel()); assertEquals(CompletionItemKind.Module, item.getKind() ); assertEquals("999999215", item.getSortText()); assertNull(item.getTextEdit()); CompletionItem resolvedItem = server.resolveCompletionItem(item).join(); assertNotNull(resolvedItem); TextEdit te = item.getTextEdit(); assertNotNull(te); assertEquals("java.sql.*;",te.getNewText()); assertNotNull(te.getRange()); Range range = te.getRange(); assertEquals(0, range.getStart().getLine()); assertEquals(7, range.getStart().getCharacter()); assertEquals(0, range.getEnd().getLine()); //Not checking the range end character }
@Test public void testJavaFormatEnable() throws Exception { String text = //@formatter:off "package org.sample ;\n\n" + " public class Baz { String name;}\n"; //@formatter:on" ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text); preferenceManager.getPreferences().setJavaFormatEnabled(false); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); String newText = TextEditUtil.apply(unit, edits); assertEquals(text, newText); }
@Test public void testRangeFormatting() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample;\n" + " public class Baz {\n"+ "\tvoid foo(){\n" + " }\n"+ " }\n" //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); Range range = new Range(new Position(2, 0), new Position(3, 5));// range around foo() DocumentRangeFormattingParams params = new DocumentRangeFormattingParams(range); params.setTextDocument(textDocument); params.setOptions(new FormattingOptions(3, true));// ident == 3 spaces List<? extends TextEdit> edits = server.rangeFormatting(params).get(); //@formatter:off String expectedText = "package org.sample;\n" + " public class Baz {\n"+ " void foo() {\n" + " }\n"+ " }\n"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
private String evaluateCodeActionCommand(Command c) throws BadLocationException, JavaModelException { Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); Assert.assertNotNull(c.getArguments()); Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit); WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0); Iterator<Entry<String, List<TextEdit>>> editEntries = we.getChanges().entrySet().iterator(); Entry<String, List<TextEdit>> entry = editEntries.next(); assertNotNull("No edits generated", entry); assertEquals("More than one resource modified", false, editEntries.hasNext()); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(entry.getKey()); assertNotNull("CU not found: " + entry.getKey(), cu); Document doc = new Document(); doc.set(cu.getSource()); return TextEditUtil.apply(doc, entry.getValue()); }
public static String apply(Document doc, Collection<? extends TextEdit> edits) throws BadLocationException { Assert.isNotNull(doc); Assert.isNotNull(edits); List<TextEdit> sortedEdits = new ArrayList<>(edits); sortByLastEdit(sortedEdits); String text = doc.get(); for (int i = sortedEdits.size() - 1; i >= 0; i--) { TextEdit te = sortedEdits.get(i); Range r = te.getRange(); if (r != null && r.getStart() != null && r.getEnd() != null) { int start = getOffset(doc, r.getStart()); int end = getOffset(doc, r.getEnd()); text = text.substring(0, start) + te.getNewText() + text.substring(end, text.length()); } } return text; }
@Test public void testUpdate_01() { StringConcatenation _builder = new StringConcatenation(); _builder.append("hello world"); _builder.newLine(); _builder.append("foo"); _builder.newLine(); _builder.append("bar"); _builder.newLine(); String _normalize = this.normalize(_builder); Document _document = new Document(1, _normalize); final Procedure1<Document> _function = (Document it) -> { StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("hello world"); _builder_1.newLine(); _builder_1.append("bar"); _builder_1.newLine(); TextEdit _change = this.change(this.position(1, 0), this.position(2, 0), ""); Assert.assertEquals(this.normalize(_builder_1), it.applyChanges( Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_change))).getContents()); }; ObjectExtensions.<Document>operator_doubleArrow(_document, _function); }
@Test public void testUpdate_02() { StringConcatenation _builder = new StringConcatenation(); _builder.append("hello world"); _builder.newLine(); _builder.append("foo"); _builder.newLine(); _builder.append("bar"); _builder.newLine(); String _normalize = this.normalize(_builder); Document _document = new Document(1, _normalize); final Procedure1<Document> _function = (Document it) -> { StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("hello world"); _builder_1.newLine(); _builder_1.append("future"); _builder_1.newLine(); _builder_1.append("bar"); _builder_1.newLine(); TextEdit _change = this.change(this.position(1, 1), this.position(1, 3), "uture"); Assert.assertEquals(this.normalize(_builder_1), it.applyChanges( Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_change))).getContents()); }; ObjectExtensions.<Document>operator_doubleArrow(_document, _function); }
@Test public void testUpdate_03() { StringConcatenation _builder = new StringConcatenation(); _builder.append("hello world"); _builder.newLine(); _builder.append("foo"); _builder.newLine(); _builder.append("bar"); String _normalize = this.normalize(_builder); Document _document = new Document(1, _normalize); final Procedure1<Document> _function = (Document it) -> { TextEdit _change = this.change(this.position(0, 0), this.position(2, 3), ""); Assert.assertEquals("", it.applyChanges( Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_change))).getContents()); }; ObjectExtensions.<Document>operator_doubleArrow(_document, _function); }
@Test public void testUpdate_nonIncrementalChange() { StringConcatenation _builder = new StringConcatenation(); _builder.append("hello world"); _builder.newLine(); _builder.append("foo"); _builder.newLine(); _builder.append("bar"); String _normalize = this.normalize(_builder); Document _document = new Document(1, _normalize); final Procedure1<Document> _function = (Document it) -> { TextEdit _change = this.change(null, null, " foo "); Assert.assertEquals(" foo ", it.applyChanges( Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_change))).getContents()); }; ObjectExtensions.<Document>operator_doubleArrow(_document, _function); }
protected String _toExpectation(final WorkspaceEdit it) { StringConcatenation _builder = new StringConcatenation(); _builder.append("changes :"); _builder.newLine(); { Set<Map.Entry<String, List<TextEdit>>> _entrySet = it.getChanges().entrySet(); for(final Map.Entry<String, List<TextEdit>> entry : _entrySet) { _builder.append("\t"); String _lastSegment = org.eclipse.emf.common.util.URI.createURI(entry.getKey()).lastSegment(); _builder.append(_lastSegment, "\t"); _builder.append(" : "); String _expectation = this.toExpectation(entry.getValue()); _builder.append(_expectation, "\t"); _builder.newLineIfNotEmpty(); } } _builder.append("documentChanges : "); _builder.newLine(); _builder.append("\t"); String _expectation_1 = this.toExpectation(it.getDocumentChanges()); _builder.append(_expectation_1, "\t"); _builder.newLineIfNotEmpty(); return _builder.toString(); }
protected void testFormatting(final Procedure1<? super FormattingConfiguration> configurator) { try { @Extension final FormattingConfiguration configuration = new FormattingConfiguration(); configuration.setFilePath(("MyModel." + this.fileExtension)); configurator.apply(configuration); final FileInfo fileInfo = this.initializeContext(configuration); DocumentFormattingParams _documentFormattingParams = new DocumentFormattingParams(); final Procedure1<DocumentFormattingParams> _function = (DocumentFormattingParams it) -> { String _uri = fileInfo.getUri(); TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri); it.setTextDocument(_textDocumentIdentifier); }; DocumentFormattingParams _doubleArrow = ObjectExtensions.<DocumentFormattingParams>operator_doubleArrow(_documentFormattingParams, _function); final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.formatting(_doubleArrow); String _contents = fileInfo.getContents(); final Document result = new Document(1, _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class))))); this.assertEquals(configuration.getExpectedText(), result.getContents()); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
protected void testRangeFormatting(final Procedure1<? super RangeFormattingConfiguration> configurator) { try { @Extension final RangeFormattingConfiguration configuration = new RangeFormattingConfiguration(); configuration.setFilePath(("MyModel." + this.fileExtension)); configurator.apply(configuration); final FileInfo fileInfo = this.initializeContext(configuration); DocumentRangeFormattingParams _documentRangeFormattingParams = new DocumentRangeFormattingParams(); final Procedure1<DocumentRangeFormattingParams> _function = (DocumentRangeFormattingParams it) -> { String _uri = fileInfo.getUri(); TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri); it.setTextDocument(_textDocumentIdentifier); it.setRange(configuration.getRange()); }; DocumentRangeFormattingParams _doubleArrow = ObjectExtensions.<DocumentRangeFormattingParams>operator_doubleArrow(_documentRangeFormattingParams, _function); final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.rangeFormatting(_doubleArrow); String _contents = fileInfo.getContents(); final Document result = new Document(1, _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class))))); this.assertEquals(configuration.getExpectedText(), result.getContents()); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
public Document applyChanges(final Iterable<? extends TextEdit> changes) { String newContent = this.contents; for (final TextEdit change : changes) { Range _range = change.getRange(); boolean _tripleEquals = (_range == null); if (_tripleEquals) { newContent = change.getNewText(); } else { final int start = this.getOffSet(change.getRange().getStart()); final int end = this.getOffSet(change.getRange().getEnd()); String _substring = newContent.substring(0, start); String _newText = change.getNewText(); String _plus = (_substring + _newText); String _substring_1 = newContent.substring(end); String _plus_1 = (_plus + _substring_1); newContent = _plus_1; } } return new Document((this.version + 1), newContent); }
@Override public CompletableFuture<List<? extends TextEdit>> rangeFormatting(final DocumentRangeFormattingParams params) { final Function1<CancelIndicator, List<? extends TextEdit>> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider resourceServiceProvider = this.languagesRegistry.getResourceServiceProvider(uri); FormattingService _get = null; if (resourceServiceProvider!=null) { _get=resourceServiceProvider.<FormattingService>get(FormattingService.class); } final FormattingService formatterService = _get; if ((formatterService == null)) { return CollectionLiterals.<TextEdit>emptyList(); } final Function2<Document, XtextResource, List<? extends TextEdit>> _function_1 = (Document document, XtextResource resource) -> { return formatterService.format(document, resource, params, cancelIndicator); }; return this.workspaceManager.<List<? extends TextEdit>>doRead(uri, _function_1); }; return this.requestManager.<List<? extends TextEdit>>runRead(_function); }
protected TextEdit toTextEdit(final Document document, final String formattedText, final int startOffset, final int length) { TextEdit _textEdit = new TextEdit(); final Procedure1<TextEdit> _function = (TextEdit it) -> { it.setNewText(formattedText); Range _range = new Range(); final Procedure1<Range> _function_1 = (Range it_1) -> { it_1.setStart(document.getPosition(startOffset)); it_1.setEnd(document.getPosition((startOffset + length))); }; Range _doubleArrow = ObjectExtensions.<Range>operator_doubleArrow(_range, _function_1); it.setRange(_doubleArrow); }; return ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function); }
List<TextEdit> addImport(String packageName, String className) { Objects.requireNonNull(packageName, "Package name is null"); Objects.requireNonNull(className, "Class name is null"); if (alreadyImported(source, packageName, className)) return Collections.emptyList(); return Collections.singletonList(insertSomehow(packageName, className)); }
private TextEdit insertSomehow(String packageName, String className) { Optional<TextEdit> done = insertInAlphabeticalOrder(packageName, className); if (done.isPresent()) return done.get(); done = insertAfterImports(packageName, className); if (done.isPresent()) return done.get(); done = insertAfterPackage(packageName, className); if (done.isPresent()) return done.get(); return insertAtTop(packageName, className); }
private Optional<TextEdit> insertInAlphabeticalOrder(String packageName, String className) { String insertLine = String.format("import %s.%s;\n", packageName, className); return source.getImports() .stream() .filter(i -> qualifiedName(i).compareTo(packageName + "." + className) > 0) .map(this::startPosition) .findFirst() .map(at -> new TextEdit(new Range(at, at), insertLine)); }
@Test public void addImportToEmpty() { String before = "package org.javacs;\n" + "\n" + "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); String after = applyEdits(before, edits); assertThat( after, equalTo( "package org.javacs;\n" + "\n" + "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }")); }
@Test public void noPackage() { String before = "import java.util.List;\n" + "\n" + "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); String after = applyEdits(before, edits); assertThat( after, equalTo( "import java.util.List;\n" + "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }")); }
@Test public void noPackageNoImports() { String before = "public class Example { void main() { } }"; List<TextEdit> edits = addImport(before, "org.javacs", "Foo"); String after = applyEdits(before, edits); assertThat( after, equalTo( "import org.javacs.Foo;\n" + "\n" + "public class Example { void main() { } }")); }
private int compareEdits(TextEdit left, TextEdit right) { int compareLines = -Integer.compare( left.getRange().getEnd().getLine(), right.getRange().getEnd().getLine()); if (compareLines != 0) return compareLines; else return -Integer.compare( left.getRange().getStart().getCharacter(), right.getRange().getEnd().getCharacter()); }
public List<TextEdit> willSaveWaitUntil(WillSaveTextDocumentParams params, IProgressMonitor monitor) { List<TextEdit> edit = new ArrayList<>(); if (monitor.isCanceled()) { return edit; } String documentUri = params.getTextDocument().getUri(); if (preferenceManager.getPreferences().isJavaSaveActionsOrganizeImportsEnabled()) { edit.addAll(handleSaveActionOrganizeImports(documentUri, monitor)); } return edit; }
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; }
private String getOrganizeImportResult(ICompilationUnit cu, WorkspaceEdit we) throws BadLocationException, CoreException { List<TextEdit> change = we.getChanges().get(JDTUtils.getFileURI(cu)); Document doc = new Document(); doc.set(cu.getSource()); return TextEditUtil.apply(doc, change); }
@Test public void testCompletion_constructor() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ " Object o = new O\n"+ " }\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "new O"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); assertFalse("No proposals were found",list.getItems().isEmpty()); List<CompletionItem> items = new ArrayList<>(list.getItems()); Comparator<CompletionItem> comparator = (CompletionItem a, CompletionItem b) -> a.getSortText().compareTo(b.getSortText()); Collections.sort(items, comparator); CompletionItem ctor = items.get(0); assertEquals("Object()", ctor.getLabel()); assertEquals("Object", ctor.getInsertText()); CompletionItem resolvedItem = server.resolveCompletionItem(ctor).join(); assertNotNull(resolvedItem); TextEdit te = resolvedItem.getTextEdit(); assertNotNull(te); assertEquals("Object()",te.getNewText()); assertNotNull(te.getRange()); Range range = te.getRange(); assertEquals(2, range.getStart().getLine()); assertEquals(17, range.getStart().getCharacter()); assertEquals(2, range.getEnd().getLine()); assertEquals(18, range.getEnd().getCharacter()); }
@Test public void testCompletion_method_withLSPV2() throws JavaModelException{ mockLSP2Client(); ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ "System.out.print(\"Hello\");\n" + "System.out.println(\" World!\");\n"+ "HashMap<String, String> map = new HashMap<>();\n"+ "map.pu\n" + " }\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "map.pu"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); CompletionItem ci = list.getItems().stream() .filter( item-> item.getLabel().matches("put\\(String \\w+, String \\w+\\) : String")) .findFirst().orElse(null); assertNotNull(ci); assertEquals("put", ci.getInsertText()); assertEquals(CompletionItemKind.Function, ci.getKind()); assertEquals("999999019", ci.getSortText()); assertNull(ci.getTextEdit()); CompletionItem resolvedItem = server.resolveCompletionItem(ci).join(); assertNotNull(resolvedItem.getTextEdit()); assertTextEdit(5, 4, 6, "put", resolvedItem.getTextEdit()); assertNotNull(resolvedItem.getAdditionalTextEdits()); List<TextEdit> edits = resolvedItem.getAdditionalTextEdits(); assertEquals(3, edits.size()); }
@Test public void testCompletion_method_withLSPV3() throws JavaModelException{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ "System.out.print(\"Hello\");\n" + "System.out.println(\" World!\");\n"+ "HashMap<String, String> map = new HashMap<>();\n"+ "map.pu\n" + " }\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "map.pu"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); CompletionItem ci = list.getItems().stream() .filter( item-> item.getLabel().matches("put\\(String \\w+, String \\w+\\) : String")) .findFirst().orElse(null); assertNotNull(ci); assertEquals("put", ci.getInsertText()); assertEquals(CompletionItemKind.Function, ci.getKind()); assertEquals("999999019", ci.getSortText()); assertNull(ci.getTextEdit()); CompletionItem resolvedItem = server.resolveCompletionItem(ci).join(); assertNotNull(resolvedItem.getTextEdit()); try { assertTextEdit(5, 4, 6, "put(${1:key}, ${2:value})", resolvedItem.getTextEdit()); } catch (ComparisonFailure e) { //In case the JDK has no sources assertTextEdit(5, 4, 6, "put(${1:arg0}, ${2:arg1})", resolvedItem.getTextEdit()); } assertNotNull(resolvedItem.getAdditionalTextEdits()); List<TextEdit> edits = resolvedItem.getAdditionalTextEdits(); assertEquals(3, edits.size()); }
@Test public void testCompletion_package() throws JavaModelException{ ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class); Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies); ICompilationUnit unit = getWorkingCopy( "src/org/sample/Baz.java", "package o"+ "public class Baz {\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "package o"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); List<CompletionItem> items = new ArrayList<>(list.getItems()); assertTrue(items.size() > 1); items.sort((i1, i2) -> i1.getSortText().compareTo(i2.getSortText())); CompletionItem item = items.get(0); // current package should appear 1st assertEquals("org.sample",item.getLabel()); CompletionItem resolvedItem = server.resolveCompletionItem(item).join(); assertNotNull(resolvedItem); TextEdit te = item.getTextEdit(); assertNotNull(te); assertEquals("org.sample", te.getNewText()); assertNotNull(te.getRange()); Range range = te.getRange(); assertEquals(0, range.getStart().getLine()); assertEquals(8, range.getStart().getCharacter()); assertEquals(0, range.getEnd().getLine()); assertEquals(15, range.getEnd().getCharacter()); }
@Test public void testDocumentFormatting() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample ;\n\n" + " public class Baz { String name;}\n" //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); //@formatter:off String expectedText = "package org.sample;\n" + "\n" + "public class Baz {\n" + " String name;\n" + "}\n"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
@Test public void testDocumentFormattingWithTabs() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample;\n\n" + "public class Baz {\n"+ " void foo(){\n"+ "}\n"+ "}\n" //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(2, false);// ident == tab DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); //@formatter:off String expectedText = "package org.sample;\n"+ "\n"+ "public class Baz {\n"+ "\tvoid foo() {\n"+ "\t}\n"+ "}\n"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
@Test public void testFormatting_onOffTags() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample;\n\n" + " public class Baz {\n"+ "// @formatter:off\n"+ "\tvoid foo(){\n"+ " }\n"+ "// @formatter:on\n"+ "}\n" //@formatter:off ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, false);// ident == tab DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); //@formatter:off String expectedText = "package org.sample;\n\n" + "public class Baz {\n"+ "// @formatter:off\n"+ "\tvoid foo(){\n"+ " }\n"+ "// @formatter:on\n"+ "}\n"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
private WorkspaceEdit recordWorkspaceEdit(final Document doc, final XtextResource resource, final IChangeSerializer.IModification<Resource> mod) { try { final XtextResourceSet rs = new XtextResourceSet(); final Resource copy = rs.createResource(resource.getURI()); String _text = resource.getParseResult().getRootNode().getText(); StringInputStream _stringInputStream = new StringInputStream(_text); copy.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap()); this.serializer.<Resource>addModification(copy, mod); final ArrayList<IEmfResourceChange> documentchanges = CollectionLiterals.<IEmfResourceChange>newArrayList(); this.serializer.applyModifications(CollectionBasedAcceptor.<IEmfResourceChange>of(documentchanges)); WorkspaceEdit _workspaceEdit = new WorkspaceEdit(); final Procedure1<WorkspaceEdit> _function = (WorkspaceEdit it) -> { Iterable<ITextDocumentChange> _filter = Iterables.<ITextDocumentChange>filter(documentchanges, ITextDocumentChange.class); for (final ITextDocumentChange documentchange : _filter) { { final Function1<ITextReplacement, TextEdit> _function_1 = (ITextReplacement replacement) -> { TextEdit _textEdit = new TextEdit(); final Procedure1<TextEdit> _function_2 = (TextEdit it_1) -> { it_1.setNewText(replacement.getReplacementText()); Position _position = doc.getPosition(replacement.getOffset()); Position _position_1 = doc.getPosition(replacement.getEndOffset()); Range _range = new Range(_position, _position_1); it_1.setRange(_range); }; return ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function_2); }; final List<TextEdit> edits = ListExtensions.<ITextReplacement, TextEdit>map(documentchange.getReplacements(), _function_1); it.getChanges().put(documentchange.getNewURI().toString(), edits); } } }; return ObjectExtensions.<WorkspaceEdit>operator_doubleArrow(_workspaceEdit, _function); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
protected String _toExpectation(final CompletionItem it) { StringConcatenation _builder = new StringConcatenation(); String _label = it.getLabel(); _builder.append(_label); { boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(it.getDetail()); boolean _not = (!_isNullOrEmpty); if (_not) { _builder.append(" ("); String _detail = it.getDetail(); _builder.append(_detail); _builder.append(")"); } } { TextEdit _textEdit = it.getTextEdit(); boolean _tripleNotEquals = (_textEdit != null); if (_tripleNotEquals) { _builder.append(" -> "); String _expectation = this.toExpectation(it.getTextEdit()); _builder.append(_expectation); } else { if (((it.getInsertText() != null) && (!Objects.equal(it.getInsertText(), it.getLabel())))) { _builder.append(" -> "); String _insertText = it.getInsertText(); _builder.append(_insertText); } } } _builder.newLineIfNotEmpty(); return _builder.toString(); }