下面列出了怎么用org.eclipse.jface.text.templates.DocumentTemplateContext的API类实例代码及写法,或者点击链接到github查看源代码。
private ICompletionProposal createProposal(ContentAssistContext context, String name, String value,
String description, String rawTemplate, Image image, boolean isGenericProposal) {
TemplateContextType contextType = getTemplateContextType();
IXtextDocument document = context.getDocument();
TemplateContext tContext = new DocumentTemplateContext(contextType, document, context.getOffset(), 0);
Region replaceRegion = context.getReplaceRegion();
// pre-populate ${name} and ${value} with given args
if (isGenericProposal) {
tContext.setVariable("name", name);
}
tContext.setVariable("value", value);
return new StyledTemplateProposal(context, name, description, rawTemplate, isGenericProposal, tContext,
replaceRegion, image);
}
/**
* @see msi.gama.lang.gaml.ui.editor.IGamlEditor#applyTemplate(org.eclipse.jface.text.templates.Template)
*/
public void applyTemplateAtTheEnd(final Template t) {
try {
final IDocument doc = getDocument();
int offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, "\n\n");
offset += 2;
final int length = 0;
final Position pos = new Position(offset, length);
final XtextTemplateContextType ct = new XtextTemplateContextType();
final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
final IRegion r = new Region(offset, length);
final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
} catch (final BadLocationException e) {
e.printStackTrace();
}
}
private boolean isReplacedAreaEmpty(TemplateContext context) {
// don't trim the buffer if the replacement area is empty
// case: surrounding empty lines with block
if (context instanceof DocumentTemplateContext) {
DocumentTemplateContext dtc= (DocumentTemplateContext) context;
if (dtc.getStart() == dtc.getCompletionOffset())
try {
IDocument document= dtc.getDocument();
int lineOffset= document.getLineInformationOfOffset(dtc.getStart()).getOffset();
//only if we are at the beginning of the line
if (lineOffset != dtc.getStart())
return false;
//Does the selection only contain whitespace characters?
if (document.get(dtc.getStart(), dtc.getEnd() - dtc.getStart()).trim().length() == 0)
return true;
} catch (BadLocationException x) {
// ignore - this may happen when the document was modified after the initial invocation, and the
// context does not track the changes properly - don't trim in that case
return true;
}
}
return false;
}
protected boolean isReplacedAreaEmpty(TemplateContext context) {
// don't trim the buffer if the replacement area is empty
// case: surrounding empty lines with block
if (context instanceof DocumentTemplateContext) {
DocumentTemplateContext dtc= (DocumentTemplateContext) context;
if (dtc.getStart() == dtc.getCompletionOffset())
try {
IDocument document= dtc.getDocument();
int lineOffset= document.getLineInformationOfOffset(dtc.getStart()).getOffset();
//only if we are at the beginning of the line
if (lineOffset != dtc.getStart())
return false;
//Does the selection only contain whitespace characters?
if (document.get(dtc.getStart(), dtc.getEnd() - dtc.getStart()).trim().length() == 0)
return true;
} catch (BadLocationException x) {
// ignore - this may happen when the document was modified after the initial invocation, and the
// context does not track the changes properly - don't trim in that case
return true;
}
}
return false;
}
@Override
protected ICompletionProposal createProposal(Template template, TemplateContext context, IRegion region,
int relevance) {
if (context instanceof DocumentTemplateContext) {
context = new SwaggerTemplateContext((DocumentTemplateContext) context);
}
return new StyledTemplateProposal(template, context, region, getImage(template), getTemplateLabel(template),
relevance);
}
public void applyTemplate(final Template t) {
// TODO Create a specific context type (with GAML specific variables ??)
final XtextTemplateContextType ct = new XtextTemplateContextType();
final IDocument doc = getDocument();
final ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
final int offset = selection.getOffset();
final int length = selection.getLength();
final Position pos = new Position(offset, length);
final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
final IRegion r = new Region(offset, length);
final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
}
@Override
protected boolean isValidTemplate(IDocument document, Template template, int offset, int length) {
String[] contextIds= getContextTypeIds(document, offset);
for (int i= 0; i < contextIds.length; i++) {
if (contextIds[i].equals(template.getContextTypeId())) {
DocumentTemplateContext context= getContext(document, template, offset, length);
return context.canEvaluate(template) || isTemplateAllowed(context, template);
}
}
return false;
}
/**
* Check whether the template is allowed eventhough the context can't evaluate it. This is
* needed because the Dropping of a template is more lenient than ctl-space invoked code assist.
*
* @param context the template context
* @param template the template
* @return true if the template is allowed
*/
private boolean isTemplateAllowed(DocumentTemplateContext context, Template template) {
int offset;
try {
if (template.getContextTypeId().equals(JavaDocContextType.ID)) {
return (offset= context.getCompletionOffset()) > 0 && Character.isWhitespace(context.getDocument().getChar(offset - 1));
} else {
return ((offset= context.getCompletionOffset()) > 0 && !isTemplateNamePart(context.getDocument().getChar(offset - 1)));
}
} catch (BadLocationException e) {
}
return false;
}
/**
* Get context
*
* @param document the document
* @param template the template
* @param offset the offset
* @param length the length
* @return the context
*/
private DocumentTemplateContext getContext(IDocument document, Template template, final int offset, int length) {
DocumentTemplateContext context;
if (template.getContextTypeId().equals(JavaDocContextType.ID)) {
context= new JavaDocContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility
.getEditorInputJavaElement(fJavaEditor, true));
} else {
context= new JavaContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility.getEditorInputJavaElement(
fJavaEditor, true));
}
return context;
}
/**
* Computes the relevance to match the relevance values generated by the
* core content assistant.
*
* @return a sensible relevance value.
*/
private int computeRelevance() {
// see org.eclipse.jdt.internal.codeassist.RelevanceConstants
final int R_DEFAULT= 0;
final int R_INTERESTING= 5;
final int R_CASE= 10;
final int R_NON_RESTRICTED= 3;
final int R_EXACT_NAME = 4;
final int R_INLINE_TAG = 31;
int base= R_DEFAULT + R_INTERESTING + R_NON_RESTRICTED;
try {
if (fContext instanceof DocumentTemplateContext) {
DocumentTemplateContext templateContext= (DocumentTemplateContext) fContext;
IDocument document= templateContext.getDocument();
String content= document.get(fRegion.getOffset(), fRegion.getLength());
if (content.length() > 0 && fTemplate.getName().startsWith(content))
base += R_CASE;
if (fTemplate.getName().equalsIgnoreCase(content))
base += R_EXACT_NAME;
if (fContext instanceof JavaDocContext)
base += R_INLINE_TAG;
}
} catch (BadLocationException e) {
// ignore - not a case sensitive match then
}
// see CompletionProposalCollector.computeRelevance
// just under keywords, but better than packages
final int TEMPLATE_RELEVANCE= 1;
return base * 16 + TEMPLATE_RELEVANCE;
}
/**
* Returns the offset of the range in the document that will be replaced by
* applying this template.
*
* @return the offset of the range in the document that will be replaced by
* applying this template
*/
protected int getReplaceOffset() {
int start;
if (fContext instanceof DocumentTemplateContext) {
DocumentTemplateContext docContext = (DocumentTemplateContext)fContext;
start= docContext.getStart();
} else {
start= fRegion.getOffset();
}
return start;
}
/**
* Returns the end offset of the range in the document that will be replaced
* by applying this template.
*
* @return the end offset of the range in the document that will be replaced
* by applying this template
*/
protected final int getReplaceEndOffset() {
int end;
if (fContext instanceof DocumentTemplateContext) {
DocumentTemplateContext docContext = (DocumentTemplateContext)fContext;
end= docContext.getEnd();
} else {
end= fRegion.getOffset() + fRegion.getLength();
}
return end;
}
/**
* Returns <code>true</code> if the proposal has a selection, e.g. will wrap some code.
*
* @return <code>true</code> if the proposals completion length is non zero
* @since 3.2
*/
private boolean isSelectionTemplate() {
if (fContext instanceof DocumentTemplateContext) {
DocumentTemplateContext ctx= (DocumentTemplateContext) fContext;
if (ctx.getCompletionLength() > 0)
return true;
}
return false;
}
/**
* Returns <code>true</code> if the proposal has a selection, e.g. will wrap some code.
*
* @return <code>true</code> if the proposals completion length is non zero
* @since 3.2
*/
private boolean isSelectionTemplate() {
if (getContext() instanceof DocumentTemplateContext) {
DocumentTemplateContext ctx= (DocumentTemplateContext) getContext();
if (ctx.getCompletionLength() > 0)
return true;
}
return false;
}
private static List<CompletionItem> getGenericSnippets(SnippetCompletionContext scc) throws JavaModelException {
List<CompletionItem> res = new ArrayList<>();
CompletionContext completionContext = scc.getCompletionContext();
char[] completionToken = completionContext.getToken();
if (completionToken == null) {
return Collections.emptyList();
}
int tokenLocation = completionContext.getTokenLocation();
JavaContextType contextType = (JavaContextType) JavaLanguageServerPlugin.getInstance().getTemplateContextRegistry().getContextType(JavaContextType.ID_STATEMENTS);
if (contextType == null) {
return Collections.emptyList();
}
ICompilationUnit cu = scc.getCompilationUnit();
IDocument document = new Document(cu.getSource());
DocumentTemplateContext javaContext = contextType.createContext(document, completionContext.getOffset(), completionToken.length, cu);
Template[] templates = null;
if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
templates = JavaLanguageServerPlugin.getInstance().getTemplateStore().getTemplates(JavaContextType.ID_STATEMENTS);
} else {
// We only support statement templates for now.
}
if (templates == null || templates.length == 0) {
return Collections.emptyList();
}
for (Template template : templates) {
if (!javaContext.canEvaluate(template)) {
continue;
}
TemplateBuffer buffer = null;
try {
buffer = javaContext.evaluate(template);
} catch (BadLocationException | TemplateException e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
continue;
}
if (buffer == null) {
continue;
}
String content = buffer.getString();
if (Strings.containsOnlyWhitespaces(content)) {
continue;
}
final CompletionItem item = new CompletionItem();
item.setLabel(template.getName());
item.setInsertText(content);
item.setDetail(template.getDescription());
setFields(item, cu);
res.add(item);
}
return res;
}
public SwaggerTemplateContext(DocumentTemplateContext context) {
super(context.getContextType(), context.getDocument(), context.getCompletionOffset(), context
.getCompletionLength());
}
/**
* Creates a concrete template context for the given region in the document. This involves finding out which
* context type is valid at the given location, and then creating a context of this type. The default implementation
* returns a <code>DocumentTemplateContext</code> for the context type at the given location.
*
* @param viewer the viewer for which the context is created
* @param region the region into <code>document</code> for which the context is created
* @return a template context that can handle template insertion at the given location, or <code>null</code>
*/
protected TemplateContext createContext(IRegion region, IDocument document) {
TemplateContextType contextType = getContextType(region);
if (contextType != null) {
return new DocumentTemplateContext(contextType, document, region.getOffset(), region.getLength());
}
return null;
}