org.eclipse.jface.text.templates.TemplateBuffer Java Examples

The following examples show how to use org.eclipse.jface.text.templates.TemplateBuffer. 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: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #2
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #3
Source File: CodeTemplateContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: DocumentSnippetTemplateContext.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example #5
Source File: SourceCodeTemplateContext.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
    * 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;
   }
 
Example #6
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #7
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: JavaDocContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #10
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
	}
 
Example #12
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: TemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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();
	}
 
Example #14
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #15
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #16
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: LangContext.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
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;
	}
 
Example #18
Source File: XtextTemplateContext.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #19
Source File: SnippetTemplateUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #20
Source File: SnippetTemplateProposal.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example #21
Source File: SwaggerTemplateContext.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #22
Source File: SwaggerTemplateContext.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #23
Source File: SourceCodeTemplateContext.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #24
Source File: XtextTemplateContext.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #25
Source File: SnippetTemplateTranslator.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public TemplateBuffer translate(Template template) throws TemplateException
{
	return super.translate(processExpansion(template.getPattern()));
}
 
Example #26
Source File: SwaggerTemplateContext.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public TemplateBuffer translate(String string) throws TemplateException {
    String withIndentation = string.replaceAll("(\r\n?)|(\n)", "$0" + indentation);
    return super.translate(withIndentation);
}
 
Example #27
Source File: SwaggerTemplateContext.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public TemplateBuffer translate(Template template) throws TemplateException {
    return translate(template.getPattern());
}
 
Example #28
Source File: SnippetCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
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;
}
 
Example #29
Source File: XbaseTemplateContext.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
	// Ensure clean state before evaluation starts
	imports.clear();
	return super.evaluateForDisplay(template);
}
 
Example #30
Source File: XtextTemplateContext.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public TemplateBuffer translate(String string) throws TemplateException {
	return super.translate(string.replaceAll("(\r\n?)|(\n)", lineDelimiter + indentation));
}