下面列出了怎么用org.eclipse.lsp4j.Position的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testRenameTypeWithResourceChanges() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes = { "package test1;\n",
"public class E|* {\n",
" public E() {\n",
" }\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);
Either<Range, PrepareRenameResult> result = prepareRename(cu, pos, "Newname");
assertNotNull(result.getLeft());
assertTrue(result.getLeft().getStart().getLine() > 0);
}
public CompletableFuture<List<? extends Location>> provideReferences(TextDocumentIdentifier textDocument,
Position position) {
if (ast == null) {
//this shouldn't happen, but let's avoid an exception if something
//goes terribly wrong.
return CompletableFuture.completedFuture(Collections.emptyList());
}
URI documentURI = URI.create(textDocument.getUri());
ASTNode offsetNode = ast.getNodeAtLineAndColumn(documentURI, position.getLine(), position.getCharacter());
if (offsetNode == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
List<ASTNode> references = GroovyASTUtils.getReferences(offsetNode, ast);
List<Location> locations = references.stream().map(node -> {
URI uri = ast.getURI(node);
return new Location(uri.toString(), GroovyLanguageServerUtils.astNodeToRange(node));
}).collect(Collectors.toList());
return CompletableFuture.completedFuture(locations);
}
public List<DocumentHighlight> findDocumentHighlights(DOMDocument xmlDocument, Position position,
CancelChecker cancelChecker) {
int offset = -1;
try {
offset = xmlDocument.offsetAt(position);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "In XMLHighlighting the client provided Position is at a BadLocation", e);
return Collections.emptyList();
}
DOMNode node = xmlDocument.findNodeAt(offset);
if (node == null) {
return Collections.emptyList();
}
List<DocumentHighlight> highlights = new ArrayList<>();
fillWithDefaultHighlights(node, position, offset, highlights, cancelChecker);
fillWithCustomHighlights(node, position, offset, highlights, cancelChecker);
return highlights;
}
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
SharedSettings sharedSettings, IComponentProvider componentProvider) {
String namespace = extractNamespace(diagnostic.getMessage());
if (StringUtils.isEmpty(namespace)) {
return;
}
DOMNode root = document.getDocumentElement();
if (root == null) {
return;
}
Position tagEnd = XMLPositionUtility.selectStartTagName(root).getEnd();
String quote = sharedSettings.getPreferences().getQuotationAsString();
// @formatter:off
CodeAction addNamespaceDecl = CodeActionFactory.insert(
"Declare '" + namespace + "' as the namespace",
tagEnd,
" xmlns=" + quote + namespace + quote,
document.getTextDocument(),
diagnostic);
// @formatter:on
codeActions.add(addNamespaceDecl);
}
public CompletableFuture<List<CompletionItem>> getCompletions(Position position) {
if (textDocumentItem != null) {
try {
ParserFileHelper parserFileHelper = new ParserFileHelperFactory().getCorrespondingParserFileHelper(textDocumentItem, position.getLine());
if (parserFileHelper != null) {
String camelComponentUri = parserFileHelper.getCamelComponentUri(textDocumentItem, position);
if (camelComponentUri != null) {
CamelURIInstance camelURIInstance = parserFileHelper.createCamelURIInstance(textDocumentItem, position, camelComponentUri);
int positionInCamelUri = parserFileHelper.getPositionInCamelURI(textDocumentItem, position);
return getCompletions(camelURIInstance, positionInCamelUri);
}
}
} catch (Exception e) {
LOGGER.error(ERROR_SEARCHING_FOR_CORRESPONDING_NODE_ELEMENTS, e);
}
}
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Test
void testProvideCompletionForYamlOnRealFileWithCamelKCloseToModelineWithURIContainingDoubleQuotesInPlainUsingMoreSpaces() throws Exception {
File f = new File("src/test/resources/workspace/samplewithModelineLikeWithDoubleQuotesInPlainInsideURIUsingMoreSpaces.yaml");
assertThat(f).exists();
try (FileInputStream fis = new FileInputStream(f)) {
CamelLanguageServer cls = initializeLanguageServer(fis, ".yaml");
CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(cls, new Position(12, 50));
CompletionItem expectedanyOrderAttributeCompletionItem = new CompletionItem("anyOrder");
expectedanyOrderAttributeCompletionItem.setDocumentation("Whether the expected messages should arrive in the same order or can be in any order.");
expectedanyOrderAttributeCompletionItem.setDeprecated(false);
expectedanyOrderAttributeCompletionItem.setDetail("boolean");
expectedanyOrderAttributeCompletionItem.setInsertText("anyOrder=false");
expectedanyOrderAttributeCompletionItem.setTextEdit(new TextEdit(new Range(new Position(12, 50), new Position(12, 50)), "anyOrder=false"));
assertThat(completions.get().getLeft()).contains(expectedanyOrderAttributeCompletionItem);
}
}
@Test
void testMemberAccessOnLocalVariableAfterDot() throws Exception {
Path filePath = srcRoot.resolve("Completion.groovy");
String uri = filePath.toUri().toString();
StringBuilder contents = new StringBuilder();
contents.append("class Completion {\n");
contents.append(" public Completion() {\n");
contents.append(" String localVar\n");
contents.append(" localVar.\n");
contents.append(" }\n");
contents.append("}");
TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Position position = new Position(3, 13);
Either<List<CompletionItem>, CompletionList> result = services
.completion(new CompletionParams(textDocument, position)).get();
Assertions.assertTrue(result.isLeft());
List<CompletionItem> items = result.getLeft();
Assertions.assertTrue(items.size() > 0);
List<CompletionItem> filteredItems = items.stream().filter(item -> {
return item.getLabel().equals("charAt") && item.getKind().equals(CompletionItemKind.Method);
}).collect(Collectors.toList());
Assertions.assertEquals(1, filteredItems.size());
}
@Test
public void testRenameTypeParameterInMethod() throws JavaModelException, BadLocationException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes = {
"package test1;\n",
"public class B<T> {\n",
" private T t;\n",
" public <U|* extends Number> inspect(U u) { return u; }\n",
"}\n"
};
StringBuilder builder = new StringBuilder();
Position pos = mergeCode(builder, codes);
ICompilationUnit cu = pack1.createCompilationUnit("B.java", builder.toString(), false, null);
Either<Range, PrepareRenameResult> result = prepareRename(cu, pos, "UU");
assertNotNull(result.getLeft());
assertTrue(result.getLeft().getStart().getLine() > 0);
}
@Test
void testMemberAccessOnClassAfterDot() throws Exception {
Path filePath = srcRoot.resolve("Completion.groovy");
String uri = filePath.toUri().toString();
StringBuilder contents = new StringBuilder();
contents.append("class Completion {\n");
contents.append(" public Completion() {\n");
contents.append(" Completion.\n");
contents.append(" }\n");
contents.append(" public static void staticMethod() {}\n");
contents.append("}");
TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Position position = new Position(2, 15);
Either<List<CompletionItem>, CompletionList> result = services
.completion(new CompletionParams(textDocument, position)).get();
Assertions.assertTrue(result.isLeft());
List<CompletionItem> items = result.getLeft();
Assertions.assertTrue(items.size() > 0);
List<CompletionItem> filteredItems = items.stream().filter(item -> {
return item.getLabel().equals("staticMethod") && item.getKind().equals(CompletionItemKind.Method);
}).collect(Collectors.toList());
Assertions.assertEquals(1, filteredItems.size());
}
private DocumentHighlight convertToHighlight(ITypeRoot unit, OccurrenceLocation occurrence)
throws JavaModelException {
DocumentHighlight h = new DocumentHighlight();
if ((occurrence.getFlags() | IOccurrencesFinder.F_WRITE_OCCURRENCE) == IOccurrencesFinder.F_WRITE_OCCURRENCE) {
h.setKind(DocumentHighlightKind.Write);
} else if ((occurrence.getFlags()
| IOccurrencesFinder.F_READ_OCCURRENCE) == IOccurrencesFinder.F_READ_OCCURRENCE) {
h.setKind(DocumentHighlightKind.Read);
}
int[] loc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset());
int[] endLoc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset() + occurrence.getLength());
h.setRange(new Range(
new Position(loc[0], loc[1]),
new Position(endLoc[0],endLoc[1])
));
return h;
}
@Test
void testMemberAccessOnLocalVariableWithExistingMethodCallExpressionOnNextLine() throws Exception {
Path filePath = srcRoot.resolve("Completion.groovy");
String uri = filePath.toUri().toString();
StringBuilder contents = new StringBuilder();
contents.append("class Completion {\n");
contents.append(" public Completion() {\n");
contents.append(" String localVar\n");
contents.append(" localVar.\n");
contents.append(" method()\n");
contents.append(" }\n");
contents.append("}");
TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Position position = new Position(3, 13);
Either<List<CompletionItem>, CompletionList> result = services
.completion(new CompletionParams(textDocument, position)).get();
Assertions.assertTrue(result.isLeft());
List<CompletionItem> items = result.getLeft();
Assertions.assertTrue(items.size() > 0);
List<CompletionItem> filteredItems = items.stream().filter(item -> {
return item.getLabel().equals("charAt") && item.getKind().equals(CompletionItemKind.Method);
}).collect(Collectors.toList());
Assertions.assertEquals(1, filteredItems.size());
}
@Test
public void testInterfaceImplementation() {
URI uri = project.getFile("src/org/sample/IFoo.java").getRawLocationURI();
String fileURI = ResourceUtils.fixURI(uri);
TextDocumentPositionParams param = new TextDocumentPositionParams();
param.setPosition(new Position(2, 20)); //Position over IFoo
param.setTextDocument(new TextDocumentIdentifier(fileURI));
List<? extends Location> implementations = handler.findImplementations(param, monitor);
assertNotNull("findImplementations should not return null", implementations);
assertEquals(2, implementations.size());
Location foo2 = implementations.get(0);
assertTrue("Unexpected implementation : " + foo2.getUri(), foo2.getUri().contains("org/sample/Foo2.java"));
assertEquals(JDTUtils.newLineRange(2, 13, 17), foo2.getRange());
Location foo3 = implementations.get(1);
assertTrue("Unexpected implementation : " + foo3.getUri(), foo3.getUri().contains("org/sample/Foo3.java"));
assertEquals(JDTUtils.newLineRange(5, 13, 17), foo3.getRange());
}
@Test
void testProvideCompletionForYamlOnRealFileWithCamelKCloseToModelineWithURIContainingDoubleQuotes() throws Exception {
File f = new File("src/test/resources/workspace/samplewithModelineLikeWithDoubleQuotesInsideURI.yaml");
assertThat(f).exists();
try (FileInputStream fis = new FileInputStream(f)) {
CamelLanguageServer cls = initializeLanguageServer(fis, ".yaml");
CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(cls, new Position(12, 47));
CompletionItem expectedanyOrderAttributeCompletionItem = new CompletionItem("anyOrder");
expectedanyOrderAttributeCompletionItem.setDocumentation("Whether the expected messages should arrive in the same order or can be in any order.");
expectedanyOrderAttributeCompletionItem.setDeprecated(false);
expectedanyOrderAttributeCompletionItem.setDetail("boolean");
expectedanyOrderAttributeCompletionItem.setInsertText("anyOrder=false");
expectedanyOrderAttributeCompletionItem.setTextEdit(new TextEdit(new Range(new Position(12, 47), new Position(12, 47)), "anyOrder=false"));
assertThat(completions.get().getLeft()).contains(expectedanyOrderAttributeCompletionItem);
}
}
@Test
public void testNoSuperMethod() throws JavaModelException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
ICompilationUnit unitA = pack1.createCompilationUnit("A.java", "package test1;\n" +
"\n" +
"public class A {\n" +
" public void run() {\n" +
" }\n" +
"}", true, null);
//@formatter:on
String uri = JDTUtils.toURI(unitA);
List<? extends Location> response = FindLinksHandler.findLinks("superImplementation", new TextDocumentPositionParams(new TextDocumentIdentifier(uri), new Position(3, 14)), new NullProgressMonitor());
assertTrue(response == null || response.isEmpty());
}
@Test
void testLocalVariableDefinitionFromAssignment() throws Exception {
Path filePath = srcRoot.resolve("Definitions.groovy");
String uri = filePath.toUri().toString();
StringBuilder contents = new StringBuilder();
contents.append("class Definitions {\n");
contents.append(" public Definitions() {\n");
contents.append(" int localVar\n");
contents.append(" localVar = 123\n");
contents.append(" }\n");
contents.append("}");
TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Position position = new Position(3, 6);
List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
.get().getLeft();
Assertions.assertEquals(1, locations.size());
Location location = locations.get(0);
Assertions.assertEquals(uri, location.getUri());
Assertions.assertEquals(2, location.getRange().getStart().getLine());
Assertions.assertEquals(8, location.getRange().getStart().getCharacter());
Assertions.assertEquals(2, location.getRange().getEnd().getLine());
Assertions.assertEquals(16, location.getRange().getEnd().getCharacter());
}
@Test
void testProvideCompletionWithDefaultValueAString() throws Exception {
CamelLanguageServer camelLanguageServer = initializeLanguageServer("// camel-k: trait=container.");
CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 28));
CompletionItem completionItem = findCompletionItemWithLabel(completions, "port-name");
assertThat(completionItem.getInsertText()).isEqualTo("port-name=http");
}
public boolean isPositionInNextToken(Position pos, Token targetToken) {
int currentIndex = getTokenIndex(targetToken);
if (currentIndex < getTokens().size() - 1) {
Token nextTkn = getTokens().get(currentIndex + 1);
return getAnalyzer().isPositionInToken(pos, nextTkn);
}
return false;
}
@Test
public void testGetEmptyDefinition() throws Exception {
List<? extends Location> definitions = handler.definition(
new TextDocumentPositionParams(new TextDocumentIdentifier("/foo/bar"), new Position(1, 1)), monitor);
assertNotNull(definitions);
assertEquals(0, definitions.size());
}
@Test
void testRetrieveNoReferenceWithDifferentDirectIds() throws Exception {
testRetrieveReferences(DIFFERENTIDS, 0, new Position(4, 18));
testRetrieveReferences(DIFFERENTIDS, 0, new Position(5, 18));
testRetrieveReferences(DIFFERENTIDS, 0, new Position(8, 18));
testRetrieveReferences(DIFFERENTIDS, 0, new Position(9, 18));
}
@Test
public void testPrepareRenameFqn_before_nok() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("package foo.bar {");
_builder.newLine();
_builder.append(" ");
_builder.append("type A {");
_builder.newLine();
_builder.append(" ");
_builder.append("foo.bar.MyType bar");
_builder.newLine();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append(" ");
_builder.append("type MyType { }");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final String model = _builder.toString();
this.initializeWithPrepareSupport();
final String uri = this.writeFile("my-type-valid.testlang", model);
TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(uri);
Position _position = new Position(2, 11);
final PrepareRenameParams params = new PrepareRenameParams(_textDocumentIdentifier, _position);
Assert.assertNull(this.languageServer.prepareRename(params).get());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private Position position(final int l, final int c) {
Position _position = new Position();
final Procedure1<Position> _function = (Position it) -> {
it.setLine(l);
it.setCharacter(c);
};
return ObjectExtensions.<Position>operator_doubleArrow(_position, _function);
}
@SuppressWarnings("unchecked")
@Test
public void testResolveImplementationsCodeLens() {
String source = "src/java/IFoo.java";
String payload = createCodeLensImplementationsRequest(source, 5, 17, 21);
CodeLens lens = getParams(payload);
Range range = lens.getRange();
assertRange(5, 17, 21, range);
CodeLens result = handler.resolve(lens, monitor);
assertNotNull(result);
//Check if command found
Command command = result.getCommand();
assertNotNull(command);
assertEquals("2 implementations", command.getTitle());
assertEquals("java.show.implementations", command.getCommand());
//Check codelens args
List<Object> args = command.getArguments();
assertEquals(3, args.size());
//Check we point to the Bar class
String sourceUri = args.get(0).toString();
assertTrue(sourceUri.endsWith("IFoo.java"));
//CodeLens position
Position p = (Position) args.get(1);
assertEquals(5, p.getLine());
assertEquals(17, p.getCharacter());
//Reference location
List<Location> locations = (List<Location>) args.get(2);
assertEquals(2, locations.size());
Location loc = locations.get(0);
assertTrue(loc.getUri().endsWith("src/java/Foo2.java"));
assertRange(5, 13, 17, loc.getRange());
}
@Override
protected TokenContext getTokenContext(Position position) {
boolean isInElement = isBetween(getFirstTknIndex(), getLastTknIndex(), position);
if (isInElement) {
Token tkn = this.analyzer.getTokenFor(position);
// Check for last token == COMMA since comma is part of the table element token
if (tkn.kind == SQLParserConstants.COMMA && getTokens().get(getLastTknIndex()).kind == SQLParserConstants.COMMA
&& getTokenIndex(tkn) == getLastTknIndex()) {
// return the TableBody context to show new column definition item
return new TokenContext(position, tkn, DdlAnalyzerConstants.Context.TABLE_BODY, this);
}
if (tkn.kind == SQLParserConstants.RPAREN) {
return new TokenContext(position, tkn, DdlAnalyzerConstants.Context.TABLE_ELEMENT, this);
}
if (optionsClause != null) {
TokenContext context = optionsClause.getTokenContext(position);
if (context != null) {
return context;
}
}
return new TokenContext(position, tkn, DdlAnalyzerConstants.Context.TABLE_ELEMENT, this);
}
return null;
}
private int getActiveParameter(Position position, List<Expression> expressions) {
for (int i = 0; i < expressions.size(); i++) {
Expression expr = expressions.get(i);
Range exprRange = GroovyLanguageServerUtils.astNodeToRange(expr);
if (position.getLine() < exprRange.getEnd().getLine()) {
return i;
}
if (position.getLine() == exprRange.getEnd().getLine()
&& position.getCharacter() <= exprRange.getEnd().getCharacter()) {
return i;
}
}
return expressions.size();
}
public static void assertRename(String value, String newText, List<TextEdit> expectedEdits)
throws BadLocationException {
int offset = value.indexOf("|");
value = value.substring(0, offset) + value.substring(offset + 1);
DOMDocument document = DOMParser.getInstance().parse(value, "test://test/test.html", null);
Position position = document.positionAt(offset);
XMLLanguageService languageService = new XMLLanguageService();
WorkspaceEdit workspaceEdit = languageService.doRename(document, position, newText);
List<TextEdit> actualEdits = workspaceEdit.getChanges().get("test://test/test.html");
assertArrayEquals(expectedEdits.toArray(), actualEdits.toArray());
}
@Override
protected TokenContext getTokenContext(Position position) {
boolean isInObject = isBetween(getFirstTknIndex(), getLastTknIndex(), position);
if (isInObject) {
Token tkn = this.analyzer.getTokenFor(position);
// Check for last token == COMMA since comma is part of the table element token
if (tkn.kind == SQLParserConstants.COMMA
&& getTokens().get(getLastTknIndex()).kind == SQLParserConstants.COMMA
&& getTokenIndex(tkn) == getLastTknIndex()) {
// return the From Clause context
return new TokenContext(position, tkn, DdlAnalyzerConstants.Context.SELECT_CLAUSE, this);
} else if (tkn.kind == SQLParserConstants.PERIOD) {
Token aliasNamePrefixToken = getTokens().get(getTokenIndex(tkn) - 1);
// check previous token and look for valid table alias
for (TableSymbol nextSymbol : getSelectClause().getQueryExpression().getFromClause()
.getTableSymbols()) {
if (nextSymbol.isAliased() && nextSymbol.getAlias().equalsIgnoreCase(aliasNamePrefixToken.image)) {
return new TokenContext(position, aliasNamePrefixToken,
DdlAnalyzerConstants.Context.TABLE_ALIAS, this);
}
}
return new TokenContext(position, aliasNamePrefixToken, DdlAnalyzerConstants.Context.SELECT_COLUMN,
this);
}
return new TokenContext(position, tkn, DdlAnalyzerConstants.Context.SELECT_COLUMN, this);
}
return null;
}
protected CompletionItem createExpectedAhcCompletionItem(int lineStart, int characterStart, int lineEnd, int characterEnd) {
CompletionItem expectedAhcCompletioncompletionItem = new CompletionItem("ahc:httpUri");
expectedAhcCompletioncompletionItem.setDocumentation(AHC_DOCUMENTATION);
expectedAhcCompletioncompletionItem.setDeprecated(false);
expectedAhcCompletioncompletionItem.setTextEdit(new TextEdit(new Range(new Position(lineStart, characterStart), new Position(lineEnd, characterEnd)), "ahc:httpUri"));
return expectedAhcCompletioncompletionItem;
}
private static void testMatchingTagPosition(String initialCursorText, String expectedCursorText) {
int offset = initialCursorText.indexOf('|');
initialCursorText = initialCursorText.substring(0, offset) + initialCursorText.substring(offset + 1);
DOMDocument xmlDocument = DOMParser.getInstance().parse(initialCursorText, "testURI", null);
Position initialCursorPosition;
Position newCursorPosition;
int newCursorOffset = -1;
try {
initialCursorPosition = xmlDocument.positionAt(offset);
newCursorPosition = XMLPositionUtility.getMatchingTagPosition(xmlDocument, initialCursorPosition);
if (newCursorPosition != null) { // a result for a matching position was found
newCursorOffset = xmlDocument.offsetAt(newCursorPosition);
}
} catch (BadLocationException e) {
fail(e.getMessage());
return;
}
StringBuffer sBuffer = new StringBuffer(initialCursorText);
String actualOutputString;
if (newCursorOffset > -1) {
actualOutputString = sBuffer.insert(newCursorOffset, "|").toString();
} else { // no matching position was found
actualOutputString = initialCursorText;
}
assertEquals(expectedCursorText, actualOutputString);
}
@Override
protected void performTest(Project project, String moduleName, TestOrganizeImportsConfiguration config)
throws Exception {
FileURI uri = getFileURIFromModuleName(moduleName);
if (config.expectedIssues.isEmpty()) {
assertNoIssues();
} else {
assertIssues(Collections.singletonMap(uri, config.expectedIssues));
}
TextDocumentIdentifier id = new TextDocumentIdentifier(uri.toString());
Range range = new Range(new Position(0, 0), new Position(0, 0));
CodeActionContext context = new CodeActionContext();
CodeActionParams params = new CodeActionParams(id, range, context);
CompletableFuture<List<Either<Command, CodeAction>>> codeActionFuture = languageServer.codeAction(params);
List<Either<Command, CodeAction>> result = codeActionFuture.join();
Command organizeImportsCommand = result.stream()
.map(e -> e.isLeft() ? e.getLeft() : e.getRight().getCommand())
.filter(cmd -> cmd != null
&& Objects.equals(cmd.getCommand(), N4JSCommandService.N4JS_ORGANIZE_IMPORTS))
.findFirst().orElse(null);
Assert.assertNotNull("code action for organize imports not found", organizeImportsCommand);
ExecuteCommandParams execParams = new ExecuteCommandParams(
organizeImportsCommand.getCommand(),
organizeImportsCommand.getArguments());
CompletableFuture<Object> execFuture = languageServer.executeCommand(execParams);
execFuture.join();
joinServerRequests();
assertContentOfFileOnDisk(uri, config.expectedCode);
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
IDocument document = viewer.getDocument();
String textToOffset = document.get().substring(0, offset);
if (isOffsetInComment(textToOffset)) {
return new ICompletionProposal[0];
}
Matcher matcher = ENDS_WITH_WORD_PATTERN.matcher(textToOffset.substring(textToOffset.lastIndexOf('\n') + 1));
matcher.matches();
String indent = matcher.group("indent"); //$NON-NLS-1$
String prefix = matcher.group("prefix"); //$NON-NLS-1$
// Use range from selection (if available) to support "surround with" style
// completions
Range range = getRangeFromSelection(document, viewer).orElseGet(() -> {
// no selection available: get range from prefix
try {
int line = document.getLineOfOffset(offset);
int lineOffset = offset - document.getLineOffset(line);
Position start = new Position(line, lineOffset - prefix.length());
Position end = new Position(line, lineOffset);
return new Range(start, end);
} catch (BadLocationException e) {
return null;
}
});
if (range == null) {
return new ICompletionProposal[] {};
}
Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(document,
capabilities -> Boolean.TRUE.equals(capabilities.getReferencesProvider()));
LSPDocumentInfo docInfo = infos.iterator().next();
ICompletionProposal[] proposals = snippets.stream().filter(s -> s.matchesPrefix(prefix))
.map(s -> s.convertToCompletionProposal(offset, docInfo, prefix, indent, range))
.toArray(ICompletionProposal[]::new);
return proposals;
}