org.eclipse.lsp4j.CompletionItem Java Examples

The following examples show how to use org.eclipse.lsp4j.CompletionItem. 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 Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSnippet_with_public() throws JavaModelException {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Test.java",
	//@formatter:off
		"package org.sample;\n" +
		"public ");
		//@formatter:off
	int[] loc = findCompletionLocation(unit, "public ");
	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("class")
					&& item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNotNull(ci);
	String text = ci.getInsertText();
	assertEquals("class Test {\n\n\t${0}\n}", text);
	ci = list.getItems().stream()
			.filter( item->  (item.getLabel().matches("interface") && item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNotNull(ci);
	text = ci.getInsertText();
	assertEquals("interface Test {\n\n\t${0}\n}", text);
}
 
Example #2
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_AnonymousDeclarationType5() throws Exception {
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"    public static void main(String[] args) {\n" +
					"        run(\"name\", new Runnable(");
	waitForBackgroundJobs();
	int[] loc = findCompletionLocation(unit, "Runnable(");
	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().startsWith("Runnable()  Anonymous Inner Type"))
			.findFirst().orElse(null);
	assertNotNull(ci);

	assertEquals("Runnable", ci.getInsertText());
	assertEquals(CompletionItemKind.Class, ci.getKind());
	assertEquals("999999372", ci.getSortText());
	assertNotNull(ci.getTextEdit());
	assertTextEdit(2, 33, 33, "(){\n" +
			"	${0}\n" +
			"}", ci.getTextEdit());
}
 
Example #3
Source Project: camel-language-server   Author: camel-tooling   File: CamelLanguageServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testProvideCompletionForYamlOnRealFileWithCamelKCloseToModelineWithURIContainingDoubleQuotesInPlain() throws Exception {
	File f = new File("src/test/resources/workspace/samplewithModelineLikeWithDoubleQuotesInPlainInsideURI.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, 45));
		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, 45), new Position(12, 45)), "anyOrder=false"));
		assertThat(completions.get().getLeft()).contains(expectedanyOrderAttributeCompletionItem);
	}
}
 
Example #4
Source Project: camel-language-server   Author: camel-tooling   File: CamelLanguageServerTest.java    License: 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 #5
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForMemberVariableOnCompleteVariableExpression() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  String memberVar\n");
	contents.append("  public Completion() {\n");
	contents.append("    memberVar\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, 7);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("memberVar") && item.getKind().equals(CompletionItemKind.Field);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #6
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSnippet_context_package() throws JavaModelException {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Test.java",
	//@formatter:off
		"package org.sample;\n");
		//@formatter:off
	int[] loc = findCompletionLocation(unit, "package ");
	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("class") && item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNull(ci);
	ci = list.getItems().stream()
			.filter( item->  (item.getLabel().matches("interface") && item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNull(ci);
}
 
Example #7
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForLocalVariableOnPartialVariableExpression() 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 void testMethod(String paramName) {\n");
	contents.append("    String localVar\n");
	contents.append("    loc\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, 7);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("localVar") && item.getKind().equals(CompletionItemKind.Variable);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #8
Source Project: lsp4j   Author: eclipse   File: EqualityTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_dataFieldURI() throws Exception {
	ICompilationUnit unit = getWorkingCopy(
		"src/java/Foo.java",
		"public class Foo {\n"+
			"	void foo() {\n"+
			"		Objec\n"+
			"	}\n"+
			"}\n");
	int[] loc = findCompletionLocation(unit, "Objec");
	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());
	for ( CompletionItem item : items) {
		@SuppressWarnings("unchecked")
		Map<String,String> data = (Map<String, String>) item.getData();
		assertNotNull(data);
		String uri = data.get(CompletionResolveHandler.DATA_FIELD_URI);
		assertTrue(isNotBlank(uri));
		assertTrue("unexpected URI prefix: " + uri, uri.matches("file://.*/src/java/Foo\\.java"));
	}
}
 
Example #10
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_class_name_contains_$() throws Exception {
	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Foo$Bar.java",
			"public class Foo$Bar {\n"+
					"    public static void main(String[] args) {\n" +
					"        new Foo\n" +
					"    }\n" +
			"}\n");
	waitForBackgroundJobs();
	int[] loc = findCompletionLocation(unit, "new Foo");
	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().startsWith("Foo$Bar"))
			.findFirst().orElse(null);
	assertNotNull(ci);

	assertEquals("Foo$Bar", ci.getInsertText());
	assertEquals(CompletionItemKind.Constructor, ci.getKind());
	assertEquals("999999115", ci.getSortText());
	assertNotNull(ci.getTextEdit());
	assertTextEdit(2, 12, 15, "Foo\\$Bar()", ci.getTextEdit());
}
 
Example #11
Source Project: camel-language-server   Author: camel-tooling   File: CompletionResolverUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void applyTextEditToCompletionItem(ILineRangeDefineable lineRangeDefineable, CompletionItem item) {
	if (lineRangeDefineable != null) {
		int line = lineRangeDefineable.getLine();
		Position pStart = new Position(line, lineRangeDefineable.getStartPositionInLine());
		Position pEnd = new Position(line, lineRangeDefineable.getEndPositionInLine());
		
		Range range = new Range(pStart, pEnd);
		
		// replace instead of insert
		if(item.getInsertText() != null) {
			item.setTextEdit(new TextEdit(range, item.getInsertText()));
		} else {
			item.setTextEdit(new TextEdit(range, item.getLabel()));
		}
	}
}
 
Example #12
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSnippet_inner_interface() throws JavaModelException {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Test.java", "package org.sample;\npublic interface Test {}\n");
	int[] loc = findCompletionLocation(unit, "package org.sample;\npublic interface Test {}\n");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();

	assertNotNull(list);
	List<CompletionItem> items = new ArrayList<>(list.getItems());
	assertFalse(items.isEmpty());
	items.sort((i1, i2) -> (i1.getSortText().compareTo(i2.getSortText())));

	CompletionItem item = items.get(6);
	assertEquals("interface", item.getLabel());
	String te = item.getInsertText();
	assertEquals("/**\n * ${1:InnerTest}\n */\npublic interface ${1:InnerTest} {\n\n\t${0}\n}", te);
}
 
Example #13
Source Project: camel-language-server   Author: camel-tooling   File: CamelCompletionInsertAndReplaceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testAttribute() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"ahc-wss:httpUri?binding=#true&amp;bufferSize=10&amp;synchronous=true\" xmlns=\"http://camel.apache.org/schema/blueprint\"/>\n", ".xml");
	Position positionBeforeBufferSizeAttribute = new Position(0, 45);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionBeforeBufferSizeAttribute);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(14);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		Range range = textEdit.getRange();
		assertThat(range.getStart().getLine()).isZero();
		assertThat(range.getStart().getCharacter()).isEqualTo(45 /* just before 'bufferSize' */);
		assertThat(range.getEnd().getLine()).isZero();
		assertThat(range.getEnd().getCharacter()).isEqualTo(55 /* end of 'bufferSize' */);
	}
}
 
Example #14
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSnippet_list_foreach() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
		"src/org/sample/Test.java",
		"package org.sample;\n" +
		"import java.util.List;\n" +
		"public class Test {\n" +
		"	public void testMethod(List<String> args) {\n" +
		"		foreach" +
		"	}\n" +
		"}"
	);
	//@formatter:on
	int[] loc = findCompletionLocation(unit, "foreach");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();

	assertNotNull(list);

	List<CompletionItem> items = new ArrayList<>(list.getItems());
	CompletionItem item = items.get(0);
	assertEquals("foreach", item.getLabel());
	String insertText = item.getInsertText();
	assertEquals("for (${1:String} ${2:string} : ${3:args}) {\n\t$TM_SELECTED_TEXT${0}\n}", insertText);
}
 
Example #15
Source Project: camel-language-server   Author: camel-tooling   File: CamelLanguageServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testDONTProvideCompletionWhenNotAfterURIEqualQuote() throws Exception {
	final TestLogAppender appender = new TestLogAppender();
	final Logger logger = Logger.getRootLogger();
	logger.addAppender(appender);
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"\" xmlns=\"http://camel.apache.org/schema/spring\"></from>\n");
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 6));
	
	assertThat(completions.get().getLeft()).isEmpty();
	assertThat(completions.get().getRight()).isNull();
	for (LoggingEvent loggingEvent : appender.getLog()) {
		if (loggingEvent.getMessage() != null) {
			assertThat((String)loggingEvent.getMessage()).doesNotContain(CamelEndpointCompletionProcessor.ERROR_SEARCHING_FOR_CORRESPONDING_NODE_ELEMENTS);
		}
	}
}
 
Example #16
Source Project: eclipse.jdt.ls   Author: eclipse   File: SyntaxLanguageServer.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
	logInfo(">> document/resolveCompletionItem");
	CompletionResolveHandler handler = new CompletionResolveHandler(preferenceManager);
	final IProgressMonitor[] monitors = new IProgressMonitor[1];
	CompletableFuture<CompletionItem> result = computeAsync((monitor) -> {
		monitors[0] = monitor;
		if ((Boolean.getBoolean(JAVA_LSP_JOIN_ON_COMPLETION))) {
			waitForLifecycleJobs(monitor);
		}
		return handler.resolve(unresolved, monitor);
	});
	result.join();
	if (monitors[0].isCanceled()) {
		result.cancel(true);
	}
	return result;
}
 
Example #17
Source Project: netbeans   Author: apache   File: TextDocumentServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params) {
    try {
        String uri = params.getTextDocument().getUri();
        FileObject file = fromUri(uri);
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        Document doc = ec.openDocument();
        int caret = getOffset(doc, params.getPosition());
        JavaCompletionTask<CompletionItem> task = JavaCompletionTask.create(caret, new ItemFactoryImpl(uri), EnumSet.noneOf(Options.class), () -> false);
        ParserManager.parse(Collections.singletonList(Source.create(doc)), task);
        List<CompletionItem> result = task.getResults();
        for (Iterator<CompletionItem> it = result.iterator(); it.hasNext();) {
            CompletionItem item = it.next();
            if (item == null) {
                it.remove();
            }
        }
        return CompletableFuture.completedFuture(Either.<List<CompletionItem>, CompletionList>forRight(new CompletionList(result)));
    } catch (IOException | ParseException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #18
Source Project: camel-language-server   Author: camel-tooling   File: CamelComponentOptionsCompletionsTest.java    License: Apache License 2.0 5 votes vote down vote up
private CompletionItem getBridgeEndpointExpectedCompletionItem(int startCharacter, int endCharacter) {
	CompletionItem completionItem = new CompletionItem("bridgeEndpoint");
	completionItem.setInsertText("bridgeEndpoint=false");
   	completionItem.setTextEdit(new TextEdit(new Range(new Position(0, startCharacter), new Position(0, endCharacter)), "bridgeEndpoint=false"));
   	completionItem.setDocumentation("If the option is true, then the Exchange.HTTP_URI header is ignored, and use the endpoint's URI for request. You may also set the throwExceptionOnFailure to be false to let the AhcProducer send all the fault response back.");
   	completionItem.setDetail("boolean");
   	completionItem.setDeprecated(false);
	return completionItem;
}
 
Example #19
Source Project: camel-language-server   Author: camel-tooling   File: CamelLanguageServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionForYamlUsingShortCutOnRealFileWithCamelKCloseToModeline() throws Exception {
	File f = new File("src/test/resources/workspace/samplewithModelineLikeAndShortCut.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(11, 13));
		assertThat(completions.get().getLeft()).contains(createExpectedAhcCompletionItem(11, 13, 11, 19));
	}
}
 
Example #20
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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("(package) java.sql", item.getDetail());
	assertEquals(CompletionItemKind.Module, item.getKind() );
	assertEquals("999999215", item.getSortText());
	assertNotNull(item.getTextEdit());
	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
}
 
Example #21
Source Project: camel-language-server   Author: camel-tooling   File: CamelKModelineCompletionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionAtTheEndOfLine() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("// camel-k: language=groovy trait=service.enabled=false ");
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 56));
	
	List<CompletionItem> completionItems = completions.get().getLeft();
	assertThat(completionItems).hasSize(10);
	checkTraitCompletionAvailable(completionItems);
}
 
Example #22
Source Project: syndesis   Author: syndesisio   File: TestDdlCompletionItemProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void testNoTableBody() {
        String stmt =
//               0123456789 123456789 123456789 123456789 123456789
                "CREATE VIEW winelist AS SELECT * FROM winelist ";

        List<CompletionItem> items = itemProvider.getCompletionItems(stmt, new Position(0, 22));
        assertEquals(1, items.size());

        items = itemProvider.getCompletionItems(stmt, new Position(0, 21));
        assertEquals(1, items.size());

        items = itemProvider.getCompletionItems(stmt, new Position(0, 47));
        assertEquals(MAX_ITEMS, items.size());
    }
 
Example #23
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: ActionScriptServices.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all items to display in the completion list at a
 * specific position in a document. Called automatically by VSCode as the
 * user types, and may not necessarily be triggered only on "." or ":".
 */
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            CompletionProvider provider = new CompletionProvider(workspaceFolderManager,
                    fileTracker, completionSupportsSnippets, frameworkSDKIsRoyale);
            return provider.completion(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #24
Source Project: syndesis   Author: syndesisio   File: CompletionItemBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public CompletionItem createKeywordItemFromItemData(String label) {
    String[] itemData = getItemData(label);
    CompletionItem ci = new CompletionItem();
    ci.setLabel(label);
    ci.setKind(CompletionItemKind.Keyword);

    if (itemData != null) {
        if (itemData.length > 1) {
            String detail = itemData[1];
            if (detail != null) {
                ci.setDetail(detail);
            }
        }

        if (itemData.length > 2) {
            String documentation = itemData[2];
            if (documentation != null) {
                ci.setDocumentation(documentation);
            }
        }

        if (itemData.length > 3) {
            String insertText = itemData[3];
            if (insertText != null) {
                ci.setInsertText(insertText);
                ci.setKind(CompletionItemKind.Snippet);
            }
        }
    }

    return ci;
}
 
Example #25
Source Project: camel-language-server   Author: camel-tooling   File: CamelKModelineCompletionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testProvideNoCompletionInPrefix() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("// camel-k: ");
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 5));
	
	assertThat(completions.get().getLeft()).isEmpty();
}
 
Example #26
Source Project: syndesis   Author: syndesisio   File: DdlCompletionItemLoader.java    License: Apache License 2.0 5 votes vote down vote up
public CompletionItem getCreateViewJoinCompletionItem(int data, String sortValue) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("CREATE VIEW with JOIN");
    ci.setInsertText(QueryExpressionHelper.CREATE_VIEW_LEFT_OUTER_JOIN_INSERT_TEXT);
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDetail(" CREATE VIEW with left join");
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText(sortValue);
    return ci;
}
 
Example #27
Source Project: camel-language-server   Author: camel-tooling   File: CompleteIdOnDirectEndpointsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testSEDAEndpointCompletion() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(new FileInputStream("src/test/resources/workspace/direct-endpoint-test.xml"), ".xml");
	Position positionInMiddleOfcomponentPart = new Position(33, 41);
	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("seda:name", "seda:processing");
	}
}
 
Example #28
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_javadocMarkdown() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class);
	Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	Mockito.when(mockCapabilies.isSupportsCompletionDocumentationMarkdown()).thenReturn(true);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/TestJavadoc.java"));
	unit.becomeWorkingCopy(null);
	String joinOnCompletion = System.getProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
	try {
		System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, "true");
		int[] loc = findCompletionLocation(unit, "inner.");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		String source = unit.getSource();
		changeDocument(unit, source, 3);
		Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, new NullProgressMonitor());
		changeDocument(unit, source, 4);
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		MarkupContent markup = resolved.getDocumentation().getRight();
		assertNotNull(markup);
		assertEquals(MarkupKind.MARKDOWN, markup.getKind());
		assertEquals("Test", markup.getValue());
	} finally {
		unit.discardWorkingCopy();
		if (joinOnCompletion == null) {
			System.clearProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
		} else {
			System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, joinOnCompletion);
		}
	}
}
 
Example #29
Source Project: camel-language-server   Author: camel-tooling   File: CamelLanguageServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionForKotlinOnRealFileWithCamelKExtension() throws Exception {
	File f = new File("src/test/resources/workspace/sample.camelk.kts");
	assertThat(f).exists();
	try (FileInputStream fis = new FileInputStream(f)) {
		CamelLanguageServer cls = initializeLanguageServer(fis, ".camelk.kts");
		CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(cls, new Position(0, 6));
		assertThat(completions.get().getLeft()).contains(createExpectedAhcCompletionItem(0, 6, 0, 18));
	}
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: SnippetCompletionProposal.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static List<CompletionItem> getSnippets(ICompilationUnit cu, CompletionContext completionContext, IProgressMonitor monitor) throws JavaModelException {
	if (cu == null) {
		throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
	}

	List<CompletionItem> res = new ArrayList<>();
	SnippetCompletionContext scc = new SnippetCompletionContext(cu, completionContext);
	res.addAll(getGenericSnippets(scc));
	res.addAll(getTypeDefinitionSnippets(scc, monitor));

	return res;
}