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 File: CompletionResolverUtils.java    From camel-language-server with 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 #2
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #3
Source File: SyntaxLanguageServer.java    From eclipse.jdt.ls with 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 #4
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 #5
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #6
Source File: CamelCompletionInsertAndReplaceTest.java    From camel-language-server with 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 #7
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #8
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #9
Source File: TextDocumentServiceImpl.java    From netbeans with 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 #10
Source File: CamelLanguageServerTest.java    From camel-language-server with 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 #11
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #12
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #13
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #14
Source File: EqualityTest.java    From lsp4j with 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 #15
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #16
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with 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 #17
Source File: CamelLanguageServerTest.java    From camel-language-server with 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 #18
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_method_withLSPV3() throws JavaModelException{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					"System.out.print(\"Hello\");\n" +
					"System.out.println(\" World!\");\n"+
					"HashMap<String, String> map = new HashMap<>();\n"+
					"map.pu\n" +
					"	}\n"+
			"}\n");

	int[] loc = findCompletionLocation(unit, "map.pu");

	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
	assertNotNull(list);
	CompletionItem ci = list.getItems().stream()
			.filter( item->  item.getLabel().matches("put\\(String \\w+, String \\w+\\) : String"))
			.findFirst().orElse(null);
	assertNotNull(ci);

	assertEquals("put", ci.getInsertText());
	assertTrue(ci.getDetail().matches("java.util.HashMap.put\\(String \\w+, String \\w+\\) : String"));
	assertEquals(CompletionItemKind.Method, ci.getKind());
	assertEquals("999999019", ci.getSortText());
	assertNotNull(ci.getTextEdit());
	try {
		assertTextEdit(5, 4, 6, "put(${1:key}, ${2:value})", ci.getTextEdit());
	} catch (ComparisonFailure e) {
		//In case the JDK has no sources
		assertTextEdit(5, 4, 6, "put(${1:arg0}, ${2:arg1})", ci.getTextEdit());
	}
	assertNotNull(ci.getAdditionalTextEdits());
	List<TextEdit> edits = ci.getAdditionalTextEdits();
	assertEquals(2, edits.size());
}
 
Example #19
Source File: DTDCompletionExtensionsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private void testCompletionFor(String xml, boolean isSnippetsSupported, Integer expectedCount,
		CompletionItem... expectedItems) throws BadLocationException {
	CompletionCapabilities completionCapabilities = new CompletionCapabilities();
	CompletionItemCapabilities completionItem = new CompletionItemCapabilities(isSnippetsSupported); // activate
																										// snippets
	completionCapabilities.setCompletionItem(completionItem);

	SharedSettings sharedSettings = new SharedSettings();
	sharedSettings.getCompletionSettings().setCapabilities(completionCapabilities);
	XMLAssert.testCompletionFor(new XMLLanguageService(), xml, "src/test/resources/catalogs/catalog.xml", null,
			null, expectedCount, sharedSettings, expectedItems);
}
 
Example #20
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static CompletionItem c(String label, TextEdit textEdit, String filterText, String documentation,
		String kind) {
	CompletionItem item = new CompletionItem();
	item.setLabel(label);
	item.setFilterText(filterText);
	item.setTextEdit(textEdit);
	if (kind == null) {
		item.setDocumentation(documentation);
	} else {
		item.setDocumentation(new MarkupContent(kind, documentation));
	}
	return item;
}
 
Example #21
Source File: CamelComponentSchemesCompletionsFuture.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<CompletionItem> apply(CamelCatalog catalog) {
	List<CompletionItem> result = getCompletionForComponents(catalog);
	if (ReferenceUtils.isReferenceComponentKind(uriElement)) {
		result.addAll(addExistingEndpointsOfSameSchemeCompletionItems());
	}
	return result;
}
 
Example #22
Source File: SnippetCompletionProposal.java    From eclipse.jdt.ls with 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;
}
 
Example #23
Source File: CamelKModelineTraitOption.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<CompletionItem>> getCompletions(int position) {
	if(getStartPositionInLine() == position) {
		return CompletableFuture.completedFuture(CamelKTraitManager.getTraitDefinitionNameCompletionItems());
	} else if(isAtTraitPropertyNameStart(position)) {
		return CompletableFuture.completedFuture(CamelKTraitManager.getTraitPropertyNameCompletionItems(traitDefinitionName));
	}
	return ICamelKModelineOptionValue.super.getCompletions(position);
}
 
Example #24
Source File: FilePathCompletionTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private void testCompletionFor(String xml, Integer expectedItemCount, CompletionItem... expectedItems)
		throws BadLocationException {
	String userDir = System.getProperty("user.dir").replace("\\", "/");
	String fileURI = "file://" + userDir + "/src/test/resources/filePathCompletion/main.xml";
	XMLAssert.testCompletionFor(xml, null, fileURI, expectedItemCount,
			expectedItems);
}
 
Example #25
Source File: TableBodyCompletionProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getAs(int data) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("AS");
    ci.setKind(CompletionItemKind.Keyword);
    ci.setData(data);
    ci.setPreselect(true);
    return ci;
}
 
Example #26
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static void testCompletionFor(XMLLanguageService xmlLanguageService, String value, String catalogPath,
		Consumer<XMLLanguageService> customConfiguration, String fileURI, Integer expectedCount,
		boolean autoCloseTags, CompletionItem... expectedItems) throws BadLocationException {

	SharedSettings settings = new SharedSettings();
	settings.getCompletionSettings().setAutoCloseTags(autoCloseTags);
	testCompletionFor(xmlLanguageService, value, catalogPath, customConfiguration, fileURI, expectedCount, settings,
			expectedItems);
}
 
Example #27
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_resolveAdditionalTextEdits() throws Exception {
	ClientPreferences mockCapabilies = mock(ClientPreferences.class);
	when(mockCapabilies.isResolveAdditionalTextEditsSupport()).thenReturn(true);
	when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					"		HashMa\n"+
					"	}\n"+
			"}\n");
	//@formatter:on
	int[] loc = findCompletionLocation(unit, "HashMa");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
	assertNotNull(list);
	assertFalse("No proposals were found",list.getItems().isEmpty());
	CompletionItem ci = list.getItems().get(0);
	assertNull(ci.getAdditionalTextEdits());
	assertEquals("HashMap - java.util", ci.getLabel());
	CompletionItem resolvedItem = server.resolveCompletionItem(ci).join();
	List<TextEdit> additionalEdits = resolvedItem.getAdditionalTextEdits();
	assertNotNull(additionalEdits);
	assertEquals(1, additionalEdits.size());
	assertEquals("import java.util.HashMap;\n\n", additionalEdits.get(0).getNewText());
}
 
Example #28
Source File: XMLCompletions.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private void collectionRegionProposals(ICompletionRequest request, ICompletionResponse response) {
	// Completion for #region
	try {
		int offset = request.getOffset();
		TextDocument document = request.getXMLDocument().getTextDocument();
		Position pos = document.positionAt(offset);
		String lineText = document.lineText(pos.getLine());
		String lineUntilPos = lineText.substring(0, pos.getCharacter());
		Matcher match = regionCompletionRegExpr.matcher(lineUntilPos);
		if (match.find()) {
			InsertTextFormat insertFormat = request.getInsertTextFormat();
			Range range = new Range(new Position(pos.getLine(), pos.getCharacter() + match.regionStart()), pos);

			String text = request.isCompletionSnippetsSupported() ? "<!-- #region $1-->" : "<!-- #region -->";
			CompletionItem beginProposal = new CompletionItem("#region");
			beginProposal.setTextEdit(new TextEdit(range, text));
			beginProposal.setDocumentation("Insert Folding Region Start");
			beginProposal.setFilterText(match.group());
			beginProposal.setSortText("za");
			beginProposal.setKind(CompletionItemKind.Snippet);
			beginProposal.setInsertTextFormat(insertFormat);
			response.addCompletionAttribute(beginProposal);

			CompletionItem endProposal = new CompletionItem("#endregion");
			endProposal.setTextEdit(new TextEdit(range, "<!-- #endregion-->"));
			endProposal.setDocumentation("Insert Folding Region End");
			endProposal.setFilterText(match.group());
			endProposal.setSortText("zb");
			endProposal.setKind(CompletionItemKind.Snippet);
			endProposal.setInsertTextFormat(InsertTextFormat.PlainText);
			response.addCompletionAttribute(endProposal);
		}
	} catch (BadLocationException e) {
		LOGGER.log(Level.SEVERE, "While performing collectRegionCompletion", e);
	}
}
 
Example #29
Source File: TableBodyCompletionProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getQueryExpressionSnippet(int data) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("AS SELECT * FROM ...");
    ci.setInsertText(" AS SELECT * FROM ${4:table_name};");
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    return ci;
}
 
Example #30
Source File: CamelExtraComponentTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
private CompletionItem createExpectedExtraComponentCompletionItem(int lineStart, int characterStart, int lineEnd, int characterEnd, String syntax, String description) {
	CompletionItem expectedAhcCompletioncompletionItem = new CompletionItem(syntax);
	expectedAhcCompletioncompletionItem.setDocumentation(description);
	expectedAhcCompletioncompletionItem.setDeprecated(false);
	expectedAhcCompletioncompletionItem.setTextEdit(new TextEdit(new Range(new Position(lineStart, characterStart), new Position(lineEnd, characterEnd)), syntax));
	return expectedAhcCompletioncompletionItem;
}