Java Code Examples for org.eclipse.jface.text.templates.TemplateBuffer#getString()

The following examples show how to use org.eclipse.jface.text.templates.TemplateBuffer#getString() . 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: 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 2
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 3
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 4
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 5
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 6
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;
}