org.eclipse.lsp4j.InsertTextFormat Java Examples

The following examples show how to use org.eclipse.lsp4j.InsertTextFormat. 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: AttributeCompletionItem.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Attribute completion item.
 * 
 * @param attrName           attribute name
 * @param canSupportSnippets true if snippets is supported to generate attribute
 *                           value and false otherwise
 * @param fullRange          the range to edit.
 * @param generateValue      true if attribute value must be generated and false
 *                           otherwise.
 * @param defaultValue       the default value of attribute.
 * @param enumerationValues  the enumeration values of attribute.
 * @param sharedSettings     the settings containing quote preferences
 */
public AttributeCompletionItem(String attrName, boolean canSupportSnippets, Range fullRange, boolean generateValue,
		String defaultValue, Collection<String> enumerationValues, SharedSettings sharedSettings) {
	super.setLabel(attrName);
	super.setKind(CompletionItemKind.Unit);
	super.setFilterText(attrName);
	StringBuilder attributeContent = new StringBuilder(attrName);
	if (generateValue) {
		// Generate attribute value content
		String attributeValue = XMLGenerator.generateAttributeValue(defaultValue, enumerationValues,
				canSupportSnippets, 1, true, sharedSettings);
		attributeContent.append(attributeValue);
	}
	super.setTextEdit(new TextEdit(fullRange, attributeContent.toString()));
	super.setInsertTextFormat(canSupportSnippets ? InsertTextFormat.Snippet : InsertTextFormat.PlainText);
}
 
Example #2
Source File: XMLReferencesCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onXMLContent(ICompletionRequest request, ICompletionResponse response) throws Exception {
	int offset = request.getOffset();
	final DOMNode node = getNodeAt(request.getNode(), offset);	
	if (node != null) {			
		XMLReferencesManager.getInstance().collect(node, n -> {
			DOMDocument doc = n.getOwnerDocument();
			Range range = XMLPositionUtility.createRange(node.getStart(), node.getEnd(), doc);
			String label = n.getNodeValue();
			CompletionItem item = new CompletionItem();
			item.setLabel(label);
			String insertText = label;
			item.setKind(CompletionItemKind.Property);
			item.setDocumentation(Either.forLeft(label));
			item.setFilterText(insertText);
			item.setTextEdit(new TextEdit(range, insertText));
			item.setInsertTextFormat(InsertTextFormat.PlainText);
			response.addCompletionItem(item);
		});
	}
}
 
Example #3
Source File: ContentModelCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private static void addCompletionItem(CMElementDeclaration elementDeclaration, DOMElement parentElement,
		String defaultPrefix, boolean forceUseOfPrefix, ICompletionRequest request, ICompletionResponse response,
		XMLGenerator generator, Set<String> tags) {
	String prefix = forceUseOfPrefix ? defaultPrefix
			: (parentElement != null ? parentElement.getPrefix(elementDeclaration.getNamespace()) : null);
	String label = elementDeclaration.getName(prefix);
	if (tags != null) {
		if (tags.contains(label)) {
			return;
		} else {
			tags.add(label);
		}
	}

	CompletionItem item = new CompletionItem(label);
	item.setFilterText(request.getFilterForStartTagName(label));
	item.setKind(CompletionItemKind.Property);
	MarkupContent documentation = XMLGenerator.createMarkupContent(elementDeclaration, request);
	item.setDocumentation(documentation);
	String xml = generator.generate(elementDeclaration, prefix,
			isGenerateEndTag(request.getNode(), request.getOffset(), label));
	item.setTextEdit(new TextEdit(request.getReplaceRange(), xml));
	item.setInsertTextFormat(InsertTextFormat.Snippet);
	response.addCompletionItem(item, true);
}
 
Example #4
Source File: HTMLCompletionExtensionsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onTagOpen(ICompletionRequest completionRequest, ICompletionResponse completionResponse)
		throws Exception {
	Range range = completionRequest.getReplaceRange();
	HTMLTag.HTML_TAGS.forEach(t -> {
		String tag = t.getTag();
		String label = t.getLabel();
		CompletionItem item = new CompletionItem();
		item.setLabel(tag);
		item.setFilterText(completionRequest.getFilterForStartTagName(tag));
		item.setKind(CompletionItemKind.Property);
		item.setDocumentation(Either.forLeft(label));
		item.setTextEdit(new TextEdit(range, "<" + tag + "/>"));
		item.setInsertTextFormat(InsertTextFormat.PlainText);
		completionResponse.addCompletionItem(item);
	});
}
 
Example #5
Source File: CompletionItemBuilder.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public CompletionItem createSnippetItem(String label, String detail, String documentation, String insertText) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel(label);
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setInsertText(insertText);
    if (documentation != null) {
        ci.setDocumentation(documentation);
    } else {
        ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    }
    if (detail != null) {
        ci.setDetail(detail);
    }

    return ci;
}
 
Example #6
Source File: DdlCompletionItemLoader.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getCreateViewInnerJoinCompletionItem(int data, String sortValue) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("CREATE VIEW with INNER JOIN");
    ci.setInsertText(QueryExpressionHelper.CREATE_VIEW_INNER_JOIN_INSERT_TEXT);
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDetail(" CREATE VIEW with inner join");
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText(sortValue);
    return ci;
}
 
Example #7
Source File: ContentAssistService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected CompletionItem toCompletionItem(ContentAssistEntry entry, int caretOffset, Position caretPosition,
		Document document) {
	CompletionItem completionItem = new CompletionItem();
	String label = entry.getLabel();
	if (label == null) {
		label = entry.getProposal();
	}
	completionItem.setLabel(label);
	completionItem.setDetail(entry.getDescription());
	completionItem.setDocumentation(entry.getDocumentation());
	String prefix = entry.getPrefix();
	if (prefix == null) {
		prefix = "";
	}
	int prefixOffset = caretOffset - prefix.length();
	Position prefixPosition = document.getPosition(prefixOffset);
	completionItem.setTextEdit(new TextEdit(new Range(prefixPosition, caretPosition), entry.getProposal()));
	completionItem.setKind(translateKind(entry));
	if (!entry.getTextReplacements().isEmpty()) {
		if (completionItem.getAdditionalTextEdits() == null) {
			completionItem.setAdditionalTextEdits(new ArrayList<>(entry.getTextReplacements().size()));
		}
		entry.getTextReplacements().forEach(
				(ReplaceRegion it) -> completionItem.getAdditionalTextEdits().add(toTextEdit(it, document)));
	}
	if (ContentAssistEntry.KIND_SNIPPET.equals(entry.getKind())) {
		completionItem.setInsertTextFormat(InsertTextFormat.Snippet);
	}
	return completionItem;
}
 
Example #8
Source File: CompletionProvider.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
private void addMXMLLanguageTagToAutoComplete(String tagName, String prefix, boolean includeOpenTagBracket, boolean includeOpenTagPrefix, CompletionList result)
{
    List<CompletionItem> items = result.getItems();
    CompletionItem item = new CompletionItem();
    item.setKind(CompletionItemKind.Keyword);
    item.setLabel("fx:" + tagName);
    if (completionSupportsSnippets)
    {
        item.setInsertTextFormat(InsertTextFormat.Snippet);
    }
    item.setFilterText(tagName);
    item.setSortText(tagName);
    StringBuilder builder = new StringBuilder();
    if (includeOpenTagBracket)
    {
        builder.append("<");
    }
    if (includeOpenTagPrefix)
    {
        builder.append(prefix);
        builder.append(IMXMLCoreConstants.colon);
    }
    builder.append(tagName);
    builder.append(">");
    builder.append("\n");
    builder.append("\t");
    if (completionSupportsSnippets)
    {
        builder.append("$0");
    }
    builder.append("\n");
    builder.append("<");
    builder.append(IMXMLCoreConstants.slash);
    builder.append(prefix);
    builder.append(IMXMLCoreConstants.colon);
    builder.append(tagName);
    builder.append(">");
    item.setInsertText(builder.toString());
    items.add(item);
}
 
Example #9
Source File: CompletionItemUtils.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
public static CompletionItem createPackageBlockItem(String packageName, boolean asSnippet)
{
	StringBuilder labelBuilder = new StringBuilder();
       labelBuilder.append(IASKeywordConstants.PACKAGE);
       if (packageName.length() > 0)
       {
           labelBuilder.append(" ");
           labelBuilder.append(packageName);
       }
       labelBuilder.append(" {}");

       StringBuilder insertTextBuilder = new StringBuilder();
       insertTextBuilder.append(IASKeywordConstants.PACKAGE);
       if (packageName.length() > 0)
       {
           insertTextBuilder.append(" ");
           insertTextBuilder.append(packageName);
       }
       insertTextBuilder.append("\n");
       insertTextBuilder.append("{");
       insertTextBuilder.append("\n");
       insertTextBuilder.append("\t");
       if (asSnippet)
       {
           insertTextBuilder.append("$0");
       }
       insertTextBuilder.append("\n");
       insertTextBuilder.append("}");

       CompletionItem packageItem = new CompletionItem();
       packageItem.setKind(CompletionItemKind.Module);
       packageItem.setLabel(labelBuilder.toString());
       packageItem.setInsertText(insertTextBuilder.toString());
       if (asSnippet)
       {
           packageItem.setInsertTextFormat(InsertTextFormat.Snippet);
	}
	return packageItem;
}
 
Example #10
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_javadocCommentNoSnippet() throws JavaModelException {
	ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class);
	Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	Mockito.when(mockCapabilies.isCompletionSnippetsSupported()).thenReturn(false);
	ICompilationUnit unit = getWorkingCopy(
	//@formatter:off
	"src/java/Foo.java",
	"public class Foo {\n"+
	"	/** */ \n"+
	"	void foo(int i, String s) {\n"+
	"	}\n"+
	"}\n");
	//@formatter:on
	int[] loc = findCompletionLocation(unit, "/**");
	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);
	assertNull(item.getInsertText());
	assertEquals(JavadocCompletionProposal.JAVA_DOC_COMMENT, item.getLabel());
	assertEquals(CompletionItemKind.Snippet, item.getKind());
	assertEquals("999999999", item.getSortText());
	assertEquals(item.getInsertTextFormat(), InsertTextFormat.PlainText);
	assertNotNull(item.getTextEdit());
	assertEquals("\n * @param i\n * @param s\n", item.getTextEdit().getNewText());
	Range range = item.getTextEdit().getRange();
	assertEquals(1, range.getStart().getLine());
	assertEquals(4, range.getStart().getCharacter());
	assertEquals(1, range.getEnd().getLine());
	assertEquals(" * @param i\n * @param s\n", item.getDocumentation().getLeft());
}
 
Example #11
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_javadocComment() throws JavaModelException {
	ICompilationUnit unit = getWorkingCopy(
	//@formatter:off
	"src/java/Foo.java",
	"public class Foo {\n"+
	"	/** */ \n"+
	"	void foo(int i, String s) {\n"+
	"	}\n"+
	"}\n");
	//@formatter:on
	int[] loc = findCompletionLocation(unit, "/**");
	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);
	assertNull(item.getInsertText());
	assertEquals(JavadocCompletionProposal.JAVA_DOC_COMMENT, item.getLabel());
	assertEquals(CompletionItemKind.Snippet, item.getKind());
	assertEquals("999999999", item.getSortText());
	assertEquals(item.getInsertTextFormat(), InsertTextFormat.Snippet);
	assertNotNull(item.getTextEdit());
	assertEquals("\n * ${0}\n * @param i\n * @param s\n", item.getTextEdit().getNewText());
	Range range = item.getTextEdit().getRange();
	assertEquals(1, range.getStart().getLine());
	assertEquals(4, range.getStart().getCharacter());
	assertEquals(1, range.getEnd().getLine());
	assertEquals(" * @param i\n * @param s\n", item.getDocumentation().getLeft());
}
 
Example #12
Source File: SnippetCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void setFields(CompletionItem ci, ICompilationUnit cu) {
	ci.setKind(CompletionItemKind.Snippet);
	ci.setInsertTextFormat(InsertTextFormat.Snippet);
	ci.setDocumentation(SnippetUtils.beautifyDocument(ci.getInsertText()));
	Map<String, String> data = new HashMap<>(3);
	data.put(CompletionResolveHandler.DATA_FIELD_URI, JDTUtils.toURI(cu));
	data.put(CompletionResolveHandler.DATA_FIELD_REQUEST_ID, "0");
	data.put(CompletionResolveHandler.DATA_FIELD_PROPOSAL_ID, "0");
	ci.setData(data);
}
 
Example #13
Source File: Snippet.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
public ICompletionProposal convertToCompletionProposal(int offset, LSPDocumentInfo info, String prefix,
		String lineIndentation, Range textRange) {
	CompletionItem item = new CompletionItem();
	item.setLabel(display);
	item.setKind(kind);
	item.setInsertTextFormat(InsertTextFormat.Snippet);

	IDocument document = info.getDocument();
	// if there is a text selection, take it, since snippets with $TM_SELECTED_TEXT
	// will want to wrap the selection.
	item.setTextEdit(new TextEdit(textRange, createReplacement(lineIndentation)));
	return new LSCompletionProposal(document, offset, item, getLanguageClient(info));
}
 
Example #14
Source File: DdlCompletionItemLoader.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getCreateViewUnionCompletionItem(int data, String sortValue) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("CREATE VIEW with UNION");
    ci.setInsertText(QueryExpressionHelper.CREATE_VIEW_UNION_INSERT_TEXT);
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDetail(" Union of two tables from single source");
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText(sortValue);
    return ci;
}
 
Example #15
Source File: DdlCompletionItemLoader.java    From syndesis with 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 #16
Source File: DdlCompletionItemLoader.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getCreateViewCompletionItem(int data, String sortValue) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("CREATE VIEW...");
    ci.setInsertText(QueryExpressionHelper.CREATE_VIEW_INSERT_TEXT);
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDetail("Simple CREATE VIEW statement");
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText(sortValue);
    return ci;
}
 
Example #17
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 #18
Source File: TableBodyCompletionProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getPrimaryKeyCompletionItem(int data) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("PRIMARY KEY (column, ...)");
    ci.setInsertText("PRIMARY KEY (${1:column})");
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText("1120");
    return ci;
}
 
Example #19
Source File: TableBodyCompletionProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CompletionItem getColumnCompletionItem(int data) {
    CompletionItem ci = new CompletionItem();
    ci.setLabel("column definition");
    ci.setInsertText("${1:column_name} ${2:datatype}");
    ci.setKind(CompletionItemKind.Snippet);
    ci.setInsertTextFormat(InsertTextFormat.Snippet);
    ci.setDocumentation(CompletionItemBuilder.beautifyDocument(ci.getInsertText()));
    ci.setData(data);
    ci.setPreselect(true);
    ci.setSortText("1100");
    return ci;
}
 
Example #20
Source File: PatchedContentAssistService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected CompletionItem toCompletionItem(ContentAssistEntry entry, int caretOffset, Position caretPosition,
		Document document) {
	CompletionItem result = super.toCompletionItem(entry, caretOffset, caretPosition, document);
	if (entry.getKind().startsWith(ContentAssistEntry.KIND_SNIPPET + ":")) {
		result.setInsertTextFormat(InsertTextFormat.Snippet);
		entry.setKind(entry.getKind().substring(ContentAssistEntry.KIND_SNIPPET.length() + 1));
	} else if (Objects.equal(entry.getKind(), ContentAssistEntry.KIND_SNIPPET)) {
		result.setInsertTextFormat(InsertTextFormat.Snippet);
	}
	result.setKind(translateKind(entry));
	return result;
}
 
Example #21
Source File: XContentAssistService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert to a completion item.
 */
protected CompletionItem toCompletionItem(ContentAssistEntry entry, int caretOffset,
		Position caretPosition, Document document) {
	CompletionItem result = new CompletionItem();
	String label = null;
	if (entry.getLabel() != null) {
		label = entry.getLabel();
	} else {
		label = entry.getProposal();
	}
	result.setLabel(label);
	result.setDetail(entry.getDescription());
	result.setDocumentation(entry.getDocumentation());
	String prefix = null;
	if (entry.getPrefix() != null) {
		prefix = entry.getPrefix();
	} else {
		prefix = "";
	}
	Position prefixPosition = document.getPosition(caretOffset - prefix.length());
	result.setTextEdit(new TextEdit(new Range(prefixPosition, caretPosition), entry.getProposal()));
	if (!entry.getTextReplacements().isEmpty()) {
		if (result.getAdditionalTextEdits() == null) {
			result.setAdditionalTextEdits(new ArrayList<>(entry.getTextReplacements().size()));
		}
		entry.getTextReplacements().forEach(it -> {
			result.getAdditionalTextEdits().add(toTextEdit(it, document));
		});
	}
	if (entry.getKind().startsWith(ContentAssistEntry.KIND_SNIPPET + ":")) {
		result.setInsertTextFormat(InsertTextFormat.Snippet);
		entry.setKind(entry.getKind().substring(ContentAssistEntry.KIND_SNIPPET.length() + 1));
	} else if (Objects.equal(entry.getKind(), ContentAssistEntry.KIND_SNIPPET)) {
		result.setInsertTextFormat(InsertTextFormat.Snippet);
	}
	result.setKind(translateKind(entry));
	return result;
}
 
Example #22
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 #23
Source File: HTMLCompletionExtensionsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onAttributeValue(String valuePrefix,
		ICompletionRequest completionRequest, ICompletionResponse completionResponse) {
	String tag = completionRequest.getCurrentTag();
	String attributeName = completionRequest.getCurrentAttributeName();
	HTMLTag htmlTag = HTMLTag.getHTMLTag(tag);
	if (htmlTag != null) {
		String[] attributes = htmlTag.getAttributes();
		if (attributes != null) {
			for (String attribute : attributes) {
				String attrName = attribute;
				String attrType = null;
				int index = attribute.indexOf(":");
				if (index != -1) {
					attrName = attribute.substring(0, index);
					attrType = attribute.substring(index + 1, attribute.length());
				}
				if (attrType != null && attributeName.equals(attrName)) {
					Range fullRange = completionRequest.getReplaceRange();
					String[] values = HTMLTag.getAttributeValues(attrType);
					for (String value : values) {
						String insertText = completionRequest.getInsertAttrValue(value);
						
						CompletionItem item = new CompletionItem();
						item.setLabel(value);
						item.setFilterText(insertText);
						item.setKind(CompletionItemKind.Unit);
						item.setTextEdit(new TextEdit(fullRange, insertText));
						item.setInsertTextFormat(InsertTextFormat.PlainText);
						completionResponse.addCompletionAttribute(item);
					}
					break;
				}
			}
		}
	}
}
 
Example #24
Source File: HTMLCompletionExtensionsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onAttributeName(boolean generateValue, ICompletionRequest completionRequest,
		ICompletionResponse completionResponse) {
	String tag = completionRequest.getCurrentTag();
	HTMLTag htmlTag = HTMLTag.getHTMLTag(tag);
	if (htmlTag != null) {
		String[] attributes = htmlTag.getAttributes();
		if (attributes != null) {
			Range replaceRange = completionRequest.getReplaceRange();
			for (String attribute : attributes) {
				int index = attribute.indexOf(":");
				if (index != -1) {
					attribute = attribute.substring(0, index);
				}
				if (!completionResponse.hasAttribute(attribute)) {
					CompletionItem item = new CompletionItem();
					item.setLabel(attribute);
					item.setKind(CompletionItemKind.Value);
					String value = generateValue ? "=\"$1\"" : "";
					item.setTextEdit(new TextEdit(replaceRange, attribute + value));
					item.setInsertTextFormat(InsertTextFormat.Snippet);
					completionResponse.addCompletionAttribute(item);
				}
			}
		}
	}
}
 
Example #25
Source File: EntitiesCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private static void fillCompletion(String name, MarkupContent documentation, Range entityRange,
		ICompletionResponse response) {
	String entityName = "&" + name + ";";
	CompletionItem item = new CompletionItem();
	item.setLabel(entityName);
	item.setKind(CompletionItemKind.Keyword);
	item.setInsertTextFormat(InsertTextFormat.PlainText);
	String insertText = entityName;
	item.setFilterText(insertText);
	item.setTextEdit(new TextEdit(entityRange, insertText));
	item.setDocumentation(documentation);
	response.addCompletionItem(item);
}
 
Example #26
Source File: DdlCompletionItemLoader.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
    private List<CompletionItem> loadItemsFromFile(String fileName) {
        List<CompletionItem> items = new ArrayList<CompletionItem>();

        try (InputStream stream = this.getClass().getResourceAsStream(fileName)) {
            JSONParser parser = new JSONParser(stream);

            // A JSON object. Key value pairs are unordered. JSONObject supports
            // java.util.Map interface.
            LinkedHashMap<String, Object> jsonObject = parser.object();

            // A JSON array. JSONObject supports java.util.List interface.
            ArrayList<?> completionItemArray = (ArrayList<?>) jsonObject.get("items");

            if (completionItemArray != null) {
                for (Object item : completionItemArray) {
                    LinkedHashMap<String, Object> itemInfo = (LinkedHashMap<String, Object>) item;
                    CompletionItem newItem = new CompletionItem();
                    newItem.setLabel((String) itemInfo.get("label"));
                    newItem.setKind(STRING_TO_KIND_MAP.get(((String) itemInfo.get("kind")).toUpperCase(Locale.US)));

                    String detail = (String) itemInfo.get("detail");
                    if (detail != null) {
                        newItem.setDetail(detail);
                    }

                    String documentation = (String) itemInfo.get("documentation");
                    if (documentation != null) {
                        newItem.setDocumentation(documentation);
                    }

                    newItem.setDeprecated(Boolean.parseBoolean((String) itemInfo.get("deprecated")));
                    newItem.setPreselect(Boolean.parseBoolean((String) itemInfo.get("preselect")));

                    String sortText = (String) itemInfo.get("sortText");
                    if (sortText != null) {
                        newItem.setSortText(sortText);
                    }

                    String insertText = (String) itemInfo.get("insertText");
                    if (insertText != null) {
                        insertText = insertText.replaceAll("\\n", "\n");
                        insertText = insertText.replaceAll("\\t", "\t");
                        newItem.setInsertText(insertText);
                    }

                    String insertTextFormat = (String) itemInfo.get("insertTextFormat");
                    if (insertTextFormat != null) {
                        if (newItem.getKind().equals(CompletionItemKind.Snippet)) {
                            newItem.setInsertTextFormat(InsertTextFormat.Snippet);
                        } else {
                            newItem.setInsertTextFormat(InsertTextFormat.PlainText);
                        }
                    }
                    // TODO: Implement quick fixes
//                  newItem.setTextEdit((TextEdit)itemInfo.get("textEdit"));
//                  newItem.setAdditionalTextEdits((List<TextEdit>)itemInfo.get("additionalTextEdits"));
//                  newItem.setCommitCharacters((List<String>)itemInfo.get("commitCharacters"));

                    String category = (String) itemInfo.get("category");
                    if (category != null && !category.isEmpty()) {
                        addItemByCategory(category, newItem);
                    } else {
                        items.add(newItem);
                    }
                }
            }

        } catch (IOException | ParseException e) {
            throw new IllegalArgumentException("Unable to parse given file: " + fileName, e);
        }

        return items;
    }
 
Example #27
Source File: CompletionItem.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * The format of the insert text. The format applies to both the `insertText` property
 * and the `newText` property of a provided `textEdit`.
 */
@Pure
public InsertTextFormat getInsertTextFormat() {
  return this.insertTextFormat;
}
 
Example #28
Source File: CompletionTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected String _toExpectation(final CompletionItem it) {
  StringConcatenation _builder = new StringConcatenation();
  {
    if (this.withKind) {
      _builder.append("(");
      CompletionItemKind _kind = it.getKind();
      _builder.append(_kind);
      {
        InsertTextFormat _insertTextFormat = it.getInsertTextFormat();
        boolean _tripleNotEquals = (_insertTextFormat != null);
        if (_tripleNotEquals) {
          _builder.append("|");
          InsertTextFormat _insertTextFormat_1 = it.getInsertTextFormat();
          _builder.append(_insertTextFormat_1);
        }
      }
      _builder.append(") ");
    }
  }
  String _label = it.getLabel();
  _builder.append(_label);
  {
    boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(it.getDetail());
    boolean _not = (!_isNullOrEmpty);
    if (_not) {
      _builder.append(" (");
      String _detail = it.getDetail();
      _builder.append(_detail);
      _builder.append(")");
    }
  }
  {
    TextEdit _textEdit = it.getTextEdit();
    boolean _tripleNotEquals_1 = (_textEdit != null);
    if (_tripleNotEquals_1) {
      _builder.append(" -> ");
      String _expectation = this.toExpectation(it.getTextEdit());
      _builder.append(_expectation);
      {
        boolean _isNullOrEmpty_1 = IterableExtensions.isNullOrEmpty(it.getAdditionalTextEdits());
        boolean _not_1 = (!_isNullOrEmpty_1);
        if (_not_1) {
          _builder.append("   + ");
          final Function1<TextEdit, String> _function = (TextEdit it_1) -> {
            return this.toExpectation(it_1);
          };
          String _join = IterableExtensions.join(ListExtensions.<TextEdit, String>map(it.getAdditionalTextEdits(), _function), "   + ");
          _builder.append(_join);
        }
      }
    } else {
      if (((it.getInsertText() != null) && (!Objects.equal(it.getInsertText(), it.getLabel())))) {
        _builder.append(" -> ");
        String _insertText = it.getInsertText();
        _builder.append(_insertText);
      }
    }
  }
  _builder.newLineIfNotEmpty();
  return _builder.toString();
}
 
Example #29
Source File: CompletionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void addDefinitionAutoCompleteActionScript(IDefinition definition, IASNode offsetNode, char nextChar, AddImportData addImportData, ILspProject project, CompletionList result)
{
    String definitionBaseName = definition.getBaseName();
    if (definitionBaseName.length() == 0)
    {
        //vscode expects all items to have a name
        return;
    }
    if (definitionBaseName.startsWith(VECTOR_HIDDEN_PREFIX))
    {
        return;
    }
    if (isDuplicateTypeDefinition(definition))
    {
        return;
    }
    if (definition instanceof ITypeDefinition)
    {
        String qualifiedName = definition.getQualifiedName();
        completionTypes.add(qualifiedName);
    }
    CompletionItem item = CompletionItemUtils.createDefinitionItem(definition, project);
    if (definition instanceof IFunctionDefinition
            && !(definition instanceof IAccessorDefinition)
            && nextChar != '('
            && completionSupportsSnippets)
    {
        IFunctionDefinition functionDefinition = (IFunctionDefinition) definition;
        if (functionDefinition.getParameters().length == 0)
        {
            item.setInsertText(definition.getBaseName() + "()");
        }
        else
        {
            item.setInsertTextFormat(InsertTextFormat.Snippet);
            item.setInsertText(definition.getBaseName() + "($0)");
            Command showParamsCommand = new Command();
            showParamsCommand.setCommand("editor.action.triggerParameterHints");
            item.setCommand(showParamsCommand);
        }
    }
    if (ASTUtils.needsImport(offsetNode, definition.getQualifiedName()))
    {
        TextEdit textEdit = CodeActionsUtils.createTextEditForAddImport(definition, addImportData);
        if(textEdit != null)
        {
            item.setAdditionalTextEdits(Collections.singletonList(textEdit));
        }
    }
    IDeprecationInfo deprecationInfo = definition.getDeprecationInfo();
    if (deprecationInfo != null)
    {
        item.setDeprecated(true);
    }
    result.getItems().add(item);
}
 
Example #30
Source File: CompletionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void addEventMetadataToAutoCompleteMXML(TypeScope typeScope, boolean isAttribute, String prefix, boolean includeOpenTagBracket, boolean includeOpenTagPrefix, char nextChar, ILspProject project, CompletionList result)
{
    ArrayList<String> eventNames = new ArrayList<>();
    IDefinition definition = typeScope.getDefinition();
    while (definition instanceof IClassDefinition)
    {
        IClassDefinition classDefinition = (IClassDefinition) definition;
        IMetaTag[] eventMetaTags = definition.getMetaTagsByName(IMetaAttributeConstants.ATTRIBUTE_EVENT);
        for (IMetaTag eventMetaTag : eventMetaTags)
        {
            String eventName = eventMetaTag.getAttributeValue(IMetaAttributeConstants.NAME_EVENT_NAME);
            if (eventName == null || eventName.length() == 0)
            {
                //vscode expects all items to have a name
                continue;
            }
            if (eventNames.contains(eventName))
            {
                //avoid duplicates!
                continue;
            }
            eventNames.add(eventName);
            IDefinition eventDefinition = project.resolveSpecifier(classDefinition, eventName);
            if (eventDefinition == null)
            {
                continue;
            }
            CompletionItem item = CompletionItemUtils.createDefinitionItem(eventDefinition, project);
            if (isAttribute
                    && completionSupportsSnippets
                    && nextChar != '=')
            {
                item.setInsertTextFormat(InsertTextFormat.Snippet);
                item.setInsertText(eventName + "=\"$0\"");
            }
            else if (!isAttribute)
            {
                StringBuilder builder = new StringBuilder();
                if (includeOpenTagBracket)
                {
                    builder.append("<");
                }
                if(includeOpenTagPrefix && prefix != null && prefix.length() > 0)
                {
                    builder.append(prefix);
                    builder.append(IMXMLCoreConstants.colon);
                }
                builder.append(eventName);
                if (completionSupportsSnippets)
                {
                    item.setInsertTextFormat(InsertTextFormat.Snippet);
                    builder.append(">");
                    builder.append("$0");
                    builder.append("</");
                    if(prefix != null && prefix.length() > 0)
                    {
                        builder.append(prefix);
                        builder.append(IMXMLCoreConstants.colon);
                    }
                    builder.append(eventName);
                    builder.append(">");
                }
                item.setInsertText(builder.toString());
            }
            result.getItems().add(item);
        }
        definition = classDefinition.resolveBaseClass(project);
    }
}