下面列出了怎么用org.eclipse.jface.text.templates.TemplateBuffer的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Shifts the variable offsets according to the current indentation level.
*
* @param buffer template buffer
* @param currentIndentation current indentation level
* @return the variable offsets according to the current indentation level
*/
@SuppressWarnings("unused")
private static TemplateVariable[] indentVariableOffsets(TemplateBuffer buffer, int currentIndentation) {
String content = buffer.getString();
TemplateVariable[] variables = buffer.getVariables();
List<Integer> lineBreaks = getLinebreaksList(content);
int line;
for (int j = 0; j < variables.length; j++) {
int[] offsets = variables[j].getOffsets();
for (int k = 0; k < offsets.length; k++) {
line = getLineOfOffset(offsets[k], lineBreaks);
offsets[k] = offsets[k] + (line * currentIndentation);
}
variables[j].setOffsets(offsets);
}
return variables;
}
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException
{
if (!canEvaluate(template))
return null;
try
{
this.template = template;
TemplateTranslator translator = new SnippetTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
finally
{
this.template = null;
}
}
/**
* Formats the template buffer.
* @param buffer
* @param context
* @throws BadLocationException
*/
public void format(TemplateBuffer buffer, TemplateContext context) throws BadLocationException {
try {
VariableTracker tracker= new VariableTracker(buffer);
IDocument document= tracker.getDocument();
internalFormat(document, context);
convertLineDelimiters(document);
if (!(context instanceof JavaDocContext) && !isReplacedAreaEmpty(context))
trimStart(document);
tracker.updateBuffer();
} catch (MalformedTreeException e) {
throw new BadLocationException();
}
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
// test that all variables are defined
Iterator<TemplateVariableResolver> iterator= getContextType().resolvers();
while (iterator.hasNext()) {
TemplateVariableResolver var= iterator.next();
if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) {
Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (!canEvaluate(template))
return null;
String pattern= changeLineDelimiter(template.getPattern(), fLineDelimiter);
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(pattern);
getContextType().resolve(buffer, this);
return buffer;
}
/**
* Evaluates a 'java' template in the context of a compilation unit
*
* @param template the template to be evaluated
* @param compilationUnit the compilation unit in which to evaluate the template
* @param position the position inside the compilation unit for which to evaluate the template
* @return the evaluated template
* @throws CoreException in case the template is of an unknown context type
* @throws BadLocationException in case the position is invalid in the compilation unit
* @throws TemplateException in case the evaluation fails
*/
public static String evaluateTemplate(Template template, ICompilationUnit compilationUnit, int position) throws CoreException, BadLocationException, TemplateException {
TemplateContextType contextType= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(template.getContextTypeId());
if (!(contextType instanceof CompilationUnitContextType))
throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, JavaTemplateMessages.JavaContext_error_message, null));
IDocument document= new Document();
if (compilationUnit != null && compilationUnit.exists())
document.set(compilationUnit.getSource());
CompilationUnitContext context= ((CompilationUnitContextType) contextType).createContext(document, position, 0, compilationUnit);
context.setForceEvaluation(true);
TemplateBuffer buffer= context.evaluate(template);
if (buffer == null)
return null;
return buffer.getString();
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(template);
getContextType().resolve(buffer, this);
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
IJavaProject project= getJavaProject();
JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
formatter.format(buffer, this);
return buffer;
}
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
IDocument doc= new Document(buffer.getString());
int nLines= doc.getNumberOfLines();
MultiTextEdit edit= new MultiTextEdit();
HashSet<Integer> removedLines= new HashSet<Integer>();
for (int i= 0; i < variables.length; i++) {
TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
if (position == null || position.getLength() > 0) {
continue;
}
int[] offsets= position.getOffsets();
for (int k= 0; k < offsets.length; k++) {
int line= doc.getLineOfOffset(offsets[k]);
IRegion lineInfo= doc.getLineInformation(line);
int offset= lineInfo.getOffset();
String str= doc.get(offset, lineInfo.getLength());
if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
int nextStart= doc.getLineOffset(line + 1);
edit.addChild(new DeleteEdit(offset, nextStart - offset));
}
}
}
edit.apply(doc, 0);
return doc.get();
}
/**
* Formats the template buffer.
* @param buffer
* @param context
* @throws BadLocationException
*/
public void format(TemplateBuffer buffer, CompilationUnitContext context) throws BadLocationException {
try {
VariableTracker tracker= new VariableTracker(buffer);
IDocument document= tracker.getDocument();
internalFormat(document, context);
convertLineDelimiters(document);
if (!(context instanceof JavaDocContext) && !isReplacedAreaEmpty(context))
trimStart(document);
tracker.updateBuffer();
} catch (MalformedTreeException e) {
throw new BadLocationException();
}
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = createTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
/**
* @since 2.3
*/
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = new TemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(template);
templateBody = buffer.getString(); // required to process multiline 'line_selection'
getContextType().resolve(buffer, this);
getIndentation();
///* Indents the variables */
//TemplateVariable[] variables = indentVariableOffsets(buffer, indentation.length());
TemplateVariable[] variables = buffer.getVariables();
/* Indents the template */
String formattedTemplate = doIndent(buffer.getString(), variables, indents);
if (cutTemplateCRLF) {
if (formattedTemplate.endsWith("\r\n")) {
formattedTemplate = formattedTemplate.substring(0, formattedTemplate.length()-2);
} else if (formattedTemplate.endsWith("\n")) {
formattedTemplate = formattedTemplate.substring(0, formattedTemplate.length()-1);
}
}
buffer.setContent(formattedTemplate, variables);
return buffer;
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = createTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
/**
* @since 2.3
*/
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = new TemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
private int getCaretOffset(TemplateBuffer buffer)
{
TemplateVariable[] variables = buffer.getVariables();
for (int i = 0; i != variables.length; i++)
{
TemplateVariable variable = variables[i];
if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME))
return variable.getOffsets()[0];
}
return buffer.getString().length();
}
/**
* Evaluate a snippet by replacing the tab stops with the default values. Note the snippet must have a scope or else
* the evaluation is not done
*
* @param snippet
* @param document
* @param position
* @return
*/
public static String evaluateSnippet(SnippetElement snippet, IDocument document, Position position)
{
String expansion = snippet.getExpansion();
Template template = new SnippetTemplate(snippet, expansion);
String scope = snippet.getScope();
if (scope != null)
{
SnippetTemplateContextType contextType = new SnippetTemplateContextType(scope);
DocumentSnippetTemplateContext context = new DocumentSnippetTemplateContext(contextType, document, position);
try
{
TemplateBuffer buffer = context.evaluate(template);
if (buffer != null)
{
return buffer.getString();
}
}
catch (Exception e)
{
IdeLog.logWarning(
CommonEditorPlugin.getDefault(),
MessageFormat.format("Error in template {0}. {1}", snippet.getDisplayName(), e.getMessage()), IDebugScopes.PRESENTATION); //$NON-NLS-1$
}
}
return expansion;
}
/**
* Creates a new tracker.
*
* @param buffer the buffer to track
* @throws MalformedTreeException
* @throws BadLocationException
*/
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
Assert.isLegal(buffer != null);
fBuffer= buffer;
fDocument= new Document(fBuffer.getString());
installJavaStuff(fDocument);
fDocument.addPositionCategory(CATEGORY);
fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
/**
* Restores any decorated regions and updates the buffer's variable offsets.
*
* @return the buffer.
* @throws MalformedTreeException
* @throws BadLocationException
*/
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
checkState();
TemplateVariable[] variables= fBuffer.getVariables();
try {
removeRangeMarkers(fPositions, fDocument, variables);
} catch (BadPositionCategoryException x) {
Assert.isTrue(false);
}
fBuffer.setContent(fDocument.get(), variables);
fDocument= null;
return fBuffer;
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
clear();
if (!canEvaluate(template))
throw new TemplateException(JavaTemplateMessages.Context_error_cannot_evaluate);
TemplateTranslator translator= new TemplateTranslator() {
@Override
protected TemplateVariable createVariable(TemplateVariableType type, String name, int[] offsets) {
// TemplateVariableResolver resolver= getContextType().getResolver(type.getName());
// return resolver.createVariable();
MultiVariable variable= new JavaVariable(type, name, offsets);
fVariables.put(name, variable);
return variable;
}
};
TemplateBuffer buffer= translator.translate(template);
getContextType().resolve(buffer, this);
rewriteImports();
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
IJavaProject project= getJavaProject();
JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
formatter.format(buffer, this);
clear();
return buffer;
}
private static TemplateVariable findVariable(TemplateBuffer buffer, String variable) {
TemplateVariable[] positions= buffer.getVariables();
for (int i= 0; i < positions.length; i++) {
TemplateVariable curr= positions[i];
if (variable.equals(curr.getType())) {
return curr;
}
}
return null;
}
private int getCaretOffset(TemplateBuffer buffer) {
TemplateVariable[] variables= buffer.getVariables();
for (int i= 0; i != variables.length; i++) {
TemplateVariable variable= variables[i];
if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME))
return variable.getOffsets()[0];
}
return buffer.getString().length();
}
@Override
public TemplateBuffer evaluate(Template template)
throws BadLocationException, TemplateException {
TemplateBuffer result = super.evaluate(template);
// After the template buffer has been created we are able to add out of range offsets
// This is not possible beforehand as it will result in an exception!
for (TemplateVariable tv : result.getVariables()) {
int[] outOfRangeOffsets = this.getVariableOutOfRangeOffsets(tv);
if (outOfRangeOffsets != null && outOfRangeOffsets.length > 0) {
int[] offsets = tv.getOffsets();
int[] newOffsets = new int[outOfRangeOffsets.length + offsets.length];
System.arraycopy(offsets, 0, newOffsets, 0, offsets.length);
for (int i = 0; i < outOfRangeOffsets.length; i++) {
newOffsets[i + offsets.length] = outOfRangeOffsets[i]; // - getAffectedSourceRegion().getOffset();
}
tv.setOffsets(newOffsets);
}
}
return result;
}
/**
* Creates a new tracker.
*
* @param buffer the buffer to track
* @throws MalformedTreeException
* @throws BadLocationException
*/
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
Assert.isLegal(buffer != null);
fBuffer= buffer;
fDocument= new Document(fBuffer.getString());
installJavaStuff(fDocument);
fDocument.addPositionCategory(CATEGORY);
fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
/**
* Restores any decorated regions and updates the buffer's variable offsets.
*
* @return the buffer.
* @throws MalformedTreeException
* @throws BadLocationException
*/
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
checkState();
TemplateVariable[] variables= fBuffer.getVariables();
try {
removeRangeMarkers(fPositions, fDocument, variables);
} catch (BadPositionCategoryException x) {
Assert.isTrue(false);
}
fBuffer.setContent(fDocument.get(), variables);
fDocument= null;
return fBuffer;
}
public TemplateBuffer evaluate(Template template, boolean fixIndentation)
throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator= new TemplateTranslator();
String pattern = template.getPattern();
// if(fixIndentation) {
// pattern = fixIndentation(pattern);
// }
TemplateBuffer buffer = translator.translate(pattern);
getContextType().resolve(buffer, this);
if(fixIndentation) {
String delimiter = TextUtilities.getDefaultLineDelimiter(getDocument());
JavaFormatter formatter = new JavaFormatter(delimiter) {
@Override
protected void indent(IDocument document) throws BadLocationException, MalformedTreeException {
simpleIndent(document);
}
};
formatter.format(buffer, this);
}
return buffer;
}
@Override
public TemplateBuffer translate(Template template) throws TemplateException {
return translate(template.getPattern());
}
@Override
public TemplateBuffer translate(String string) throws TemplateException {
return super.translate(string.replaceAll("(\r\n?)|(\n)", lineDelimiter + indentation));
}
@Override
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
// Ensure clean state before evaluation starts
imports.clear();
return super.evaluateForDisplay(template);
}
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;
}
@Override
public TemplateBuffer translate(Template template) throws TemplateException {
return translate(template.getPattern());
}
@Override
public TemplateBuffer translate(String string) throws TemplateException {
String withIndentation = string.replaceAll("(\r\n?)|(\n)", "$0" + indentation);
return super.translate(withIndentation);
}