org.eclipse.lsp4j.Position Java Examples

The following examples show how to use org.eclipse.lsp4j.Position. 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: GroovyServicesDefinitionTests.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: DocumentHighlightHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: XMLHighlighting.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: TargetNamespace_2CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #7
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: ReferenceProvider.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: CamelEndpointCompletionProcessor.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #12
Source File: ImplementationsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: CamelLanguageServerTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #14
Source File: CamelLanguageServerTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #15
Source File: FindLinksHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #16
Source File: CompleteIdOnDirectEndpointsTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testVMEndpointCompletion() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(new FileInputStream("src/test/resources/workspace/direct-endpoint-test.xml"), ".xml");
	Position positionInMiddleOfcomponentPart = new Position(25, 39);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionInMiddleOfcomponentPart);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(2);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		assertThat(textEdit.getNewText()).isIn("vm:name", "vm:processing");
	}
}
 
Example #17
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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);

	WorkspaceEdit edit = getRenameEdit(cu, pos, "UU");
	assertNotNull(edit);
	assertEquals(edit.getChanges().size(), 1);

	assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))),
			"package test1;\n" +
			"public class B<T> {\n" +
			"	private T t;\n" +
			"	public <UU extends Number> inspect(UU u) { return u; }\n" +
			"}\n"
			);
}
 
Example #18
Source File: StringLSP4J.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** @return string for given element */
public String toString(Range range) {
	if (range == null) {
		return "";
	}
	Position start = range.getStart();
	Position end = range.getEnd();
	String stringPosStr = start.getLine() + ":" + start.getCharacter();
	String endPosStr = end.getLine() + ":" + end.getCharacter();
	return "[" + stringPosStr + " - " + endPosStr + "]";
}
 
Example #19
Source File: ReferencesProcessorTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testRetrieveASingleDirectReferenceFor_to_whenUsingCamelNamespacePrefix() throws Exception {
	Location res = testRetrieveReferences(SINGLE_REFERENCE_WITH_NAMESPACE_PREFIX, 1, new Position(5, 26)).get(0);
	Range range = res.getRange();
	assertThat(range.getStart().getLine()).isEqualTo(8);
	assertThat(range.getEnd().getLine()).isEqualTo(8);
}
 
Example #20
Source File: NavigateToDefinitionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void testClass(String className, int line, int column) throws JavaModelException {
	String uri = ClassFileUtil.getURI(project, className);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri);
	List<? extends Location> definitions = handler
			.definition(new TextDocumentPositionParams(identifier, new Position(line, column)), monitor);
	assertNotNull(definitions);
	assertEquals("No definition found for " + className, 1, definitions.size());
	assertNotNull(definitions.get(0).getUri());
	assertTrue(definitions.get(0).getRange().getStart().getLine() >= 0);
}
 
Example #21
Source File: IncrementalParsingTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBasicChangeMultipleChanges() {
	String text = 
		"<>\r\n" + // <-- inserting 'a' in tag name
		"  <b>\r\n" +
		"  </>\r\n" + // <-- inserting 'b' in tag name
		"</a>\r\n";
	
	String expectedText = 
		"<a>\r\n" + // <-- inserted 'a' in tag name
		"  <b>\r\n" +
		"  </b>\r\n" + // <-- inserted 'b' in tag name
		"</a>\r\n";

	TextDocument document = new TextDocument(text, "uri");
	document.setIncremental(true);

	Range range1 = new Range(new Position(0, 1), new Position(0,1));
	TextDocumentContentChangeEvent change1 = new TextDocumentContentChangeEvent(range1, 0, "a");

	Range range2 = new Range(new Position(2, 4), new Position(2,4));
	TextDocumentContentChangeEvent change2 = new TextDocumentContentChangeEvent(range2, 0, "b");
	
	ArrayList<TextDocumentContentChangeEvent> changes = new ArrayList<TextDocumentContentChangeEvent>();
	// The order they are added in is backwards with the largest offset being first
	changes.add(change2);
	changes.add(change1);

	document.update(changes);

	assertEquals(expectedText, document.getText());

}
 
Example #22
Source File: GroovyServicesSignatureHelpTests.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testSignatureHelpOnMethod() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class SignatureHelp {\n");
	contents.append("  public SignatureHelp() {\n");
	contents.append("    method(\n");
	contents.append("  }\n");
	contents.append("  public void method(int param0) {}\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, 11);
	SignatureHelp signatureHelp = services.signatureHelp(new TextDocumentPositionParams(textDocument, position))
			.get();
	List<SignatureInformation> signatures = signatureHelp.getSignatures();
	Assertions.assertEquals(1, signatures.size());
	SignatureInformation signature = signatures.get(0);
	Assertions.assertEquals("public void method(int param0)", signature.getLabel());
	List<ParameterInformation> params = signature.getParameters();
	Assertions.assertEquals(1, params.size());
	ParameterInformation param0 = params.get(0);
	Assertions.assertEquals("int param0", param0.getLabel().get());
	Assertions.assertEquals((int) 0, (int) signatureHelp.getActiveSignature());
	Assertions.assertEquals((int) 0, (int) signatureHelp.getActiveParameter());
}
 
Example #23
Source File: CamelEndpointOptionDuplicateTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest(name="{4} - Position ({1},{2})")
@MethodSource("data")
void testProvideCompletionForCamelBlueprintNamespace(String textToTest, int line, int character, String testNameQualification, String excludedString) throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(textToTest);
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(line, character));
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items.size()).isPositive();
	if (excludedString != null) {
		for (CompletionItem item : items) {
			assertThat(item.getLabel()).doesNotStartWith(excludedString);
		}
	} 
	assertThat(completions.get().getRight()).isNull();
}
 
Example #24
Source File: MissingEnumQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMissingEnumConstant() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("   public enum Numbers { One, Two};\n");
	buf.append("    public void testing() {\n");
	buf.append("        Numbers n = Numbers.One;\n");
	buf.append("        switch (n) {\n");
	buf.append("        case Two:\n");
	buf.append("            return;\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range range = new Range(new Position(5, 16), new Position(5, 17));
	setIgnoredCommands(ActionMessages.GenerateConstructorsAction_ellipsisLabel, ActionMessages.GenerateConstructorsAction_label);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, range);
	assertEquals(2, codeActions.size());
	Either<Command, CodeAction> codeAction = codeActions.get(0);
	CodeAction action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add 'default' case", action.getTitle());
	TextEdit edit = getTextEdit(codeAction);
	assertEquals("\n        default:\n            break;", edit.getNewText());
	codeAction = codeActions.get(1);
	action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add missing case statements", action.getTitle());
	edit = getTextEdit(codeAction);
	assertEquals("\n        case One:\n            break;\n        default:\n            break;", edit.getNewText());
}
 
Example #25
Source File: CamelExtraComponentTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testUpdateOfConfig() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"\" xmlns=\"http://camel.apache.org/schema/blueprint\"></from>\n");
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 11));
	assertThat(completions.get().getLeft()).contains(createBasicExpectedCompletionItem());
	
	
	String component = "{\n" + 
			" \"component\": {\n" + 
			"    \"kind\": \"component\",\n" + 
			"    \"scheme\": \"aSecondcomponent\",\n" + 
			"    \"syntax\": \"aSecondcomponent:withsyntax\",\n" + 
			"    \"title\": \"A Second Component\",\n" + 
			"    \"description\": \"Description of my second component.\",\n" + 
			"    \"label\": \"\",\n" + 
			"    \"deprecated\": false,\n" + 
			"    \"deprecationNote\": \"\",\n" + 
			"    \"async\": false,\n" + 
			"    \"consumerOnly\": true,\n" + 
			"    \"producerOnly\": false,\n" + 
			"    \"lenientProperties\": false,\n" + 
			"    \"javaType\": \"org.test.ASecondComponent\",\n" + 
			"    \"firstVersion\": \"1.0.0\",\n" + 
			"    \"groupId\": \"org.test\",\n" + 
			"    \"artifactId\": \"camel-asecondcomponent\",\n" + 
			"    \"version\": \"3.0.0-RC3\"\n" + 
			"  },\n" + 
			"  \"componentProperties\": {\n" + 
			"  },\n" + 
			"  \"properties\": {\n" + 
			"  }\n" + 
			"}";
	DidChangeConfigurationParams params = new DidChangeConfigurationParams(createMapSettingsWithComponent(component));
	camelLanguageServer.getWorkspaceService().didChangeConfiguration(params);
	
	assertThat(getCompletionFor(camelLanguageServer, new Position(0, 11)).get().getLeft())
	.contains(createExpectedExtraComponentCompletionItem(0, 11, 0, 11, "aSecondcomponent:withsyntax", "Description of my second component."));
}
 
Example #26
Source File: CamelPropertiesComponentOptionNameCompletionTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testInsertAndReplace() throws Exception {
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = retrieveCompletion(new Position(0, 27), "camel.component.acomponent.awrongtoreplace=aValue");
	CompletionItem expectedCompletionItem = new CompletionItem("aComponentProperty");
	expectedCompletionItem.setInsertText("aComponentProperty");
	expectedCompletionItem.setDocumentation("A parameter description");
	expectedCompletionItem.setDeprecated(false);
	expectedCompletionItem.setDetail(String.class.getName());
	expectedCompletionItem.setTextEdit(new TextEdit(new Range(new Position(0, 27), new Position(0, 42)), "aComponentProperty"));
	assertThat(completions.get().getLeft()).contains(expectedCompletionItem);
}
 
Example #27
Source File: XMLPositionUtilityTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
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);
	}
 
Example #28
Source File: AbstractOrganizeImportsTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: SnippetContentAssistProcessor.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: SelectionRangeHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testJavadoc() throws CoreException {
	SelectionRange range = getSelectionRange("org.sample.Foo4", new Position(9, 31));
	assertTrue(validateSelectionRange(range, new Range(new Position(9, 4), new Position(9, 40)), // text element
			new Range(new Position(9, 4), new Position(9, 40)), // tag element
			new Range(new Position(8, 1), new Position(10, 4)), // javadoc
			new Range(new Position(8, 1), new Position(16, 2)), // method declaration
			TYPE_DECL_RANGE, COMP_UNIT_RAGE));
}