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

The following examples show how to use org.eclipse.jface.text.templates.Template. 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: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String getSetterComment(ICompilationUnit cu, String typeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter)
		throws CoreException {
	String templateName= CodeTemplateContextType.SETTERCOMMENT_ID;
	Template template= getCodeTemplate(templateName, cu.getJavaProject());
	if (template == null) {
		return null;
	}

	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
	context.setCompilationUnitVariables(cu);
	context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
	context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
	context.setVariable(CodeTemplateContextType.FIELD, fieldName);
	context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType);
	context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName);
	context.setVariable(CodeTemplateContextType.PARAM, paramName);

	return evaluateTemplate(context, template);
}
 
Example #2
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 #3
Source File: SnippetsCompletionProcessor.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public static void insertAsTemplate(ITextViewer textViewer, final IRegion region, String templateText,
		CommandElement commandElement)
{
	SnippetsCompletionProcessor snippetsCompletionProcessor = new SnippetsCompletionProcessor();
	Template template = new SnippetTemplate(commandElement, templateText);
	TemplateContext context = snippetsCompletionProcessor.createContext(textViewer, region);
	SnippetTemplateProposal completionProposal = (SnippetTemplateProposal) snippetsCompletionProcessor
			.createProposal(template, context, region, 0);
	completionProposal.setTemplateProposals(new ICompletionProposal[] { completionProposal });
	completionProposal.apply(textViewer, '0', SWT.NONE, region.getOffset());

	Point selection = completionProposal.getSelection(textViewer.getDocument());
	if (selection != null)
	{
		textViewer.setSelectedRange(selection.x, selection.y);
		textViewer.revealRange(selection.x, selection.y);
	}
}
 
Example #4
Source File: UnimplementedCodeCleanUp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String getOverridingMethodComment() {
	String templateName= CodeTemplateContextType.OVERRIDECOMMENT_ID;

	Template template= getCodeTemplate(templateName);
	if (template == null)
		return ""; //$NON-NLS-1$

	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), null, "\n"); //$NON-NLS-1$

	context.setVariable(CodeTemplateContextType.FILENAME, "Face.java"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.PACKAGENAME, "test"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.PROJECTNAME, "TestProject"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, "Face"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, "method"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.RETURN_TYPE, "void"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, "test.IFace#foo()"); //$NON-NLS-1$

	return evaluateTemplate(template, context);
}
 
Example #5
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Don't use this method directly, use CodeGeneration.
 * 
 * @param templateID the template id of the type body to get. Valid id's are
 *            {@link CodeTemplateContextType#CLASSBODY_ID},
 *            {@link CodeTemplateContextType#INTERFACEBODY_ID},
 *            {@link CodeTemplateContextType#ENUMBODY_ID},
 *            {@link CodeTemplateContextType#ANNOTATIONBODY_ID},
 * @param cu the compilation unit to which the template is added
 * @param typeName the type name
 * @param lineDelim the line delimiter to use
 * @return return the type body template or <code>null</code>
 * @throws CoreException thrown if the template could not be evaluated
 * @see org.eclipse.jdt.ui.CodeGeneration#getTypeBody(String, ICompilationUnit, String, String)
 */
public static String getTypeBody(String templateID, ICompilationUnit cu, String typeName, String lineDelim) throws CoreException {
	if (!VALID_TYPE_BODY_TEMPLATES.contains(templateID)) {
		throw new IllegalArgumentException("Invalid code template ID: " + templateID); //$NON-NLS-1$
	}

	Template template= getCodeTemplate(templateID, cu.getJavaProject());
	if (template == null) {
		return null;
	}
	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim);
	context.setCompilationUnitVariables(cu);
	context.setVariable(CodeTemplateContextType.TYPENAME, typeName);

	return evaluateTemplate(context, template);
}
 
Example #6
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean hasCompatibleContextType(Template template) {
	String key= getKey();
	if (template.matches(key, getContextType().getId()))
		return true;

	if (fCompatibleContextTypeIds == null)
		return false;

	Iterator<String> iter= fCompatibleContextTypeIds.iterator();
	while (iter.hasNext()) {
		if (template.matches(key, iter.next()))
			return true;
	}

	return false;
}
 
Example #7
Source File: ProjectTemplateStore.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void load() throws IOException {
	if (fProjectStore != null) {
		fProjectStore.load();

		Set<String> datas= new HashSet<String>();
		TemplatePersistenceData[] data= fProjectStore.getTemplateData(false);
		for (int i= 0; i < data.length; i++) {
			datas.add(data[i].getId());
		}

		data= fInstanceStore.getTemplateData(false);
		for (int i= 0; i < data.length; i++) {
			TemplatePersistenceData orig= data[i];
			if (!datas.contains(orig.getId())) {
				TemplatePersistenceData copy= new TemplatePersistenceData(new Template(orig.getTemplate()), orig.isEnabled(), orig.getId());
				fProjectStore.add(copy);
				copy.setDeleted(true);
			}
		}
	}
}
 
Example #8
Source File: GamlTemplateFactory.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static Template callToAction(final StatementDescription sd) {
	final String name = sd.getName();
	final Iterable<IDescription> args = sd.getFormalArgs();
	final StringBuilder sb = new StringBuilder(100);
	sb.append("(");
	for (final IDescription arg : args) {
		sb.append(arg.getName()).append(": ").append("${the_").append(arg.getName()).append("}, ");
	}
	final int length = sb.length();
	if (length > 0) {
		sb.setLength(length - 2);
	}
	sb.append(")");
	final Template t =
			new Template("A call to action " + name, "A call to action " + name + " will all its arguments",
					getContextId(), "do " + name + sb.toString() + ";" + Strings.LN, true);
	return t;
}
 
Example #9
Source File: EditTemplateDialog.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, 
		ContextTypeRegistry registry, TemplatesLanguageConfiguration configuration, 
		IEditedResourceProvider resourceProvider, String languageName) {
	super(parent);
	this.configuration = configuration;
	this.resourceProvider = resourceProvider;
	this.languageName = languageName;

	String title= edit
		? TemplateDialogMessages.EditTemplateDialog_title_edit
		: TemplateDialogMessages.EditTemplateDialog_title_new;
	setTitle(title);

	this.fTemplate= template;
	fIsNameModifiable= isNameModifiable;

	List<String[]> contexts= Lists.newArrayList();
	for (Iterator<TemplateContextType> it= Iterators.filter(registry.contextTypes(), TemplateContextType.class); it.hasNext();) {
		TemplateContextType type= it.next();
		contexts.add(new String[] { type.getId(), type.getName() });
	}
	fContextTypes= contexts.toArray(new String[contexts.size()][]);
	fContextTypeRegistry= registry;
}
 
Example #10
Source File: AdvancedTemplatesPreferencePage.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void updateViewerInput() {
	IStructuredSelection selection= (IStructuredSelection) getTableViewer().getSelection();
	if (selection.size() == 1) {
		TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
		Template template= data.getTemplate();
		String name = template.getName();
		TemplateContextType contextType = getContextTypeRegistry().getContextType(template.getContextTypeId());
		if (contextType != null) {
			String prefix = 
					"templates for " + grammarAccess.getGrammar().getName() +
					"'" + name + "'" + " for " + getContextTypeForGrammar(contextType) + ">>";
			String editablePart = template.getPattern();
			String suffix = "";
			partialEditor.updateModel(prefix, editablePart, suffix);
		} else {
			partialEditor.updateModel("", template.getPattern(), "");
		}
	} else {
		partialEditor.updateModel("", "", "");
	}
}
 
Example #11
Source File: Activator.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
private void addNamedTemplates(String inlineContextId, String namedContextId, String key) {
    Template[] schemaTemplates = templateStore.getTemplates(inlineContextId);
    for (int i = 0; i < schemaTemplates.length; i++) {
        Template schemaTemplate = schemaTemplates[i];
        Template template = createNamedTemplate(schemaTemplate, namedContextId, key);
        templateStore.add(new TemplatePersistenceData(template, true));
    }
}
 
Example #12
Source File: JavaTemplatesPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: CodeTemplateBlock.java    From typescript.java with MIT License 5 votes vote down vote up
protected void updateSourceViewerInput(List selection) {
	if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) {
		return;
	}
	if (selection.size() == 1 && selection.get(0) instanceof TemplatePersistenceData) {
		TemplatePersistenceData data = (TemplatePersistenceData) selection.get(0);
		Template template = data.getTemplate();
		TemplateContextType type = JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry()
				.getContextType(template.getContextTypeId());
		fTemplateProcessor.setContextType(type);
		fPatternViewer.getDocument().set(template.getPattern());
	} else {
		fPatternViewer.getDocument().set(""); //$NON-NLS-1$
	}
}
 
Example #14
Source File: JsonContentAssistProcessor.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: PyStringCodeCompletion.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param ret OUT: this is where the completions are stored
 */
private void fillWithEpydocFields(CompletionRequest request,
        List<ICompletionProposalHandle> ret) {
    try {
        Region region = new Region(request.documentOffset - request.qlen, request.qlen);
        IImageHandle image = PyCodeCompletionImages.getImageForType(IToken.TYPE_EPYDOC);
        TemplateContext context = createContext(region, request.doc);

        char c = request.doc.getChar(request.documentOffset - request.qualifier.length() - 1);

        boolean createFields = c == '@' || c == ':';
        if (createFields) {
            String lineContentsToCursor = PySelection.getLineContentsToCursor(request.doc,
                    request.documentOffset - request.qualifier.length() - 1);
            if (lineContentsToCursor.trim().length() != 0) {
                //Only create if @param or :param is the first thing in the line.
                createFields = false;
            }
        }
        if (createFields) {
            //ok, looking for epydoc filters
            for (int i = 0; i < EPYDOC_FIELDS.length; i++) {
                String f = EPYDOC_FIELDS[i];
                if (f.startsWith(request.qualifier)) {
                    Template t = new Template(f, EPYDOC_FIELDS[i + 2], "", EPYDOC_FIELDS[i + 1], false);
                    ret.add(
                            CompletionProposalFactory.get().createPyTemplateProposalForTests(
                                    t, context, region, image, 5));
                }
                i += 2;
            }
        }
    } catch (BadLocationException e) {
        //just ignore it
    }
}
 
Example #16
Source File: JavaTemplatesPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Image getImage(Template template) {
	String contextId= template.getContextTypeId();
	if (SWTContextType.ID_ALL.equals(contextId) || SWTContextType.ID_STATEMENTS.equals(contextId) || SWTContextType.ID_MEMBERS.equals(contextId))
		return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SWT_TEMPLATE);
	return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE);
}
 
Example #17
Source File: GamlTemplateFactory.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static Template speciesWithSkill(final String skill) {
	final StringBuilder comment = new StringBuilder(200);
	comment.append(beginComment);
	dump(inheritedAttributes, GamaSkillRegistry.INSTANCE.getVariablesForSkill(skill), comment);
	dump(inheritedActions, GamaSkillRegistry.INSTANCE.getActionsForSkill(skill), comment);
	comment.append(endComment);
	return new Template("A species with the skill " + skill,
			"Defines a species that implements the skill named " + skill, getContextId(),
			"species ${species_name} skills: [" + skill + "]" + body(comment.toString()), true);
}
 
Example #18
Source File: CodeTemplateBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void edit(TemplatePersistenceData data) {
	Template newTemplate= new Template(data.getTemplate());
	EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, JavaPlugin.getDefault().getCodeTemplateContextRegistry());
	if (dialog.open() == Window.OK) {
		// changed
		data.setTemplate(dialog.getTemplate());
		fCodeTemplateTree.refresh(data);
		fCodeTemplateTree.selectElements(new StructuredSelection(data));
	}
}
 
Example #19
Source File: StyledTemplateProposal.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
static private Template createTemplate(ContentAssistContext context, String displayLabel, String description,
		String rawTemplate) {

	boolean trailingComma = hasTrailingComma(context);
	if (trailingComma) {
		rawTemplate = rawTemplate + ",";
	}

	return new Template(displayLabel, description, "", rawTemplate, true);
}
 
Example #20
Source File: CodeTemplateBlock.java    From typescript.java with MIT License 5 votes vote down vote up
private void edit(TemplatePersistenceData data) {
	Template newTemplate = new Template(data.getTemplate());
	EditTemplateDialog dialog = new EditTemplateDialog(getShell(), newTemplate, true, false,
			JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry());
	if (dialog.open() == Window.OK) {
		// changed
		data.setTemplate(dialog.getTemplate());
		fCodeTemplateTree.refresh(data);
		fCodeTemplateTree.selectElements(new StructuredSelection(data));
	}
}
 
Example #21
Source File: UnimplementedCodeCleanUp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getMethodBody() {
	String templateName= CodeTemplateContextType.METHODSTUB_ID;
	Template template= getCodeTemplate(templateName);
	if (template == null)
		return ""; //$NON-NLS-1$

	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), null, "\n"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, "method"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, "Face"); //$NON-NLS-1$
	context.setVariable(CodeTemplateContextType.BODY_STATEMENT, ""); //$NON-NLS-1$
	return evaluateTemplate(template, context);
}
 
Example #22
Source File: TemplateSet.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean exists(Template template) {
	for (Iterator<Template> iterator = fTemplates.iterator(); iterator.hasNext();) {
		Template anotherTemplate = iterator.next();

		if (template.equals(anotherTemplate))
			return true;
	}

	return false;
}
 
Example #23
Source File: CheckCfgTemplateProposalProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adds the populated check configuration.
 *
 * @param templateContext
 *          the template context
 * @param context
 *          the context
 * @param acceptor
 *          the acceptor
 */
@SuppressWarnings("all")
private void addCatalogConfigurations(final TemplateContext templateContext, final ContentAssistContext context, final ITemplateAcceptor acceptor) {
  final String templateName = "Add all registered catalogs"; //$NON-NLS-1$
  final String templateDescription = "configures all missing catalogs"; //$NON-NLS-1$

  final String contextTypeId = templateContext.getContextType().getId();
  if (context.getRootModel() instanceof CheckConfiguration) {
    final CheckConfiguration conf = (CheckConfiguration) context.getRootModel();
    List<IEObjectDescription> allElements = Lists.newArrayList(scopeProvider.getScope(conf, CheckcfgPackage.Literals.CONFIGURED_CATALOG__CATALOG).getAllElements());

    StringBuilder builder = new StringBuilder();
    for (IEObjectDescription description : allElements) {
      if (description.getEObjectOrProxy() instanceof CheckCatalog) {
        CheckCatalog catalog = (CheckCatalog) description.getEObjectOrProxy();
        if (catalog.eIsProxy()) {
          catalog = (CheckCatalog) EcoreUtil.resolve(catalog, conf);
        }
        if (isCatalogConfigured(conf, catalog)) {
          continue;
        } else if (allElements.indexOf(description) > 0) {
          builder.append(Strings.newLine());
        }
        final String catalogName = qualifiedNameValueConverter.toString(description.getQualifiedName().toString());
        builder.append("catalog ").append(catalogName).append(" {}").append(Strings.newLine()); //$NON-NLS-1$ //$NON-NLS-2$
      }

    }

    if (builder.length() > 0) {
      builder.append("${cursor}"); //$NON-NLS-1$
      Template t = new Template(templateName, templateDescription, contextTypeId, builder.toString(), true);
      TemplateProposal tp = createProposal(t, templateContext, context, images.forConfiguredCatalog(), getRelevance(t));
      acceptor.accept(tp);
    }
  }
}
 
Example #24
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Template getCodeTemplate(String id, IJavaProject project) {
	if (project == null)
		return JavaPlugin.getDefault().getCodeTemplateStore().findTemplateById(id);
	ProjectTemplateStore projectStore= new ProjectTemplateStore(project.getProject());
	try {
		projectStore.load();
	} catch (IOException e) {
		JavaPlugin.log(e);
	}
	return projectStore.findTemplateById(id);
}
 
Example #25
Source File: CheckCfgTemplateProposalProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Image getImage(final Template template) {
  if (Strings.equal("CheckConfiguration", template.getName())) { // see templates.xml //$NON-NLS-1$
    return images.forCheckConfiguration();
  } else if (Strings.equal("Add a catalog", template.getName())) { // see templates.xml //$NON-NLS-1$
    return images.forConfiguredCatalog();
  }
  return super.getImage(template);
}
 
Example #26
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 #27
Source File: CheckTemplateProposalProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Image getImage(final Template template) {
  if (Strings.equal("Catalog", template.getName())) { //$NON-NLS-1$
    return images.forCheckCatalog();
  } else if (Strings.equal("Check", template.getName())) { //$NON-NLS-1$
    return images.forCheck(SeverityKind.ERROR);
  } else if (Strings.equal("Category", template.getName())) { //$NON-NLS-1$
    return images.forCategory();
  } else if (Strings.equal("Severity range", template.getName())) { //$NON-NLS-1$
    return images.forSeverityRange();
  }
  return super.getImage(template);
}
 
Example #28
Source File: PostfixTemplateEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void complete(ITextViewer viewer, int completionPosition, ICompilationUnit compilationUnit) {
	IDocument document = viewer.getDocument();

	if (!(getContextType() instanceof JavaStatementPostfixContextType))
		return;

	Point selection = viewer.getSelectedRange();

	String selectedText = null;
	if (selection.y != 0) {
		return;
	}

	JavaStatementPostfixContext context = ((JavaStatementPostfixContextType) getContextType()).createContext(document, completionPosition, selection.y, compilationUnit, currentNode, parentNode);
	context.setVariable("selection", selectedText); //$NON-NLS-1$
	int start = context.getStart();
	int end = context.getEnd();
	IRegion region = new Region(start, end - start);

	Template[] templates = JavaPlugin.getDefault().getTemplateStore().getTemplates(getContextType().getId());

	for (int i = 0; i != templates.length; i++) {
		Template template = templates[i];
		if (context.canEvaluate(template)) {
			getProposals().add(new PostfixTemplateProposal(template, context, region, getImage()));
		}
	}
}
 
Example #29
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 #30
Source File: GamlTemplateFactory.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param proto
 * @return
 */
public static Template from(final OperatorProto proto) {
	String description = proto.getMainDoc();
	if (description == null) {
		description = "Template for using operator " + proto.getName();
	}
	return new Template("Operator " + proto.getName(), description, getContextId(), proto.getPattern(true), true);
}