类org.eclipse.jface.text.templates.TemplateContext源码实例Demo

下面列出了怎么用org.eclipse.jface.text.templates.TemplateContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: n4js   文件: JSONProposalFactory.java
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);
}
 
@Override
public void createTemplates(ContentAssistContext context, ITemplateAcceptor acceptor) {
	if (!acceptor.canAcceptMoreTemplates())
		return;
	TemplateContext[] templateContexts = createTemplateContexts(context);
	if (templateContexts == null || templateContexts.length == 0)
		return;

	ITemplateAcceptor nullSafe = new NullSafeTemplateAcceptor(acceptor);
	for(TemplateContext templateContext: templateContexts) {
		if (!nullSafe.canAcceptMoreTemplates())
			return;
		templateContext.setVariable("selection", context.getSelectedText()); // name of the selection variables {line, word}_selection //$NON-NLS-1$
		createTemplates(templateContext, context, nullSafe);
	}
}
 
@Override
protected void createTemplates(final TemplateContext templateContext, final ContentAssistContext context, final ITemplateAcceptor acceptor) {
  if (templateContext.getContextType().getId().equals("com.avaloq.tools.ddk.checkcfg.CheckCfg.ConfiguredCheck")) { //$NON-NLS-1$
    addConfiguredCheckTemplates(templateContext, context, acceptor);
    return;
  } else if (templateContext.getContextType().getId().equals("com.avaloq.tools.ddk.checkcfg.CheckCfg.kw_catalog")) { //$NON-NLS-1$
    addCatalogConfigurations(templateContext, context, acceptor);
  }
  TemplateContextType contextType = templateContext.getContextType();
  Template[] templates = templateStore.getTemplates(contextType.getId());
  for (Template template : templates) {

    if (!acceptor.canAcceptMoreTemplates()) {
      return;
    }
    if (validate(template, templateContext)) {
      acceptor.accept(createProposal(template, templateContext, context, getImage(template), getRelevance(template)));
    }
  }
}
 
源代码4 项目: APICloud-Studio   文件: TabStopVariableResolver.java
@SuppressWarnings("unchecked")
@Override
public void resolve(TemplateVariable variable, TemplateContext context)
{
	if (!variable.getVariableType().getParams().isEmpty())
	{
		String[] values = (String[]) variable.getVariableType().getParams().toArray(new String[0]);
		variable.setValues(values);
		variable.setUnambiguous(false);
		variable.setResolved(true);
	}
	else
	{
		super.resolve(variable, context);
		setEvaluationString(variable.getName());
	}
}
 
源代码5 项目: Pydev   文件: AssistSurroundWith.java
private ICompletionProposalHandle createProposal(PySelection ps, IImageCache imageCache, IPyEdit edit,
        final String startIndent, IRegion region, int iComp, String comp, TemplateContext context) {
    Template t = new Template("Surround with", SURROUND_WITH_COMPLETIONS[iComp + 1], "", comp, false);
    if (context != null) {
        PyTemplateProposal proposal = new PyTemplateProposal(t, context, region,
                ImageCache.asImage(imageCache.get(UIConstants.COMPLETION_TEMPLATE)), 5) {
            @Override
            public String getAdditionalProposalInfo() {
                return startIndent + super.getAdditionalProposalInfo();
            }
        };
        return proposal;
    } else {
        //In tests
        return CompletionProposalFactory.get().createPyCompletionProposal(comp, region.getOffset(),
                region.getLength(), 0, 0);
    }
}
 
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);
	}
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	List<String> params= variable.getVariableType().getParams();
	String param;
	if (params.size() == 0)
		param= fDefaultType;
	else
		param= params.get(0);

	JavaContext jc= (JavaContext) context;
	MultiVariable mv= (MultiVariable) variable;

	String reference= jc.addImport(param);
	mv.setValue(reference);
	mv.setUnambiguous(true);
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	variable.setUnambiguous(true);
	variable.setValue(""); //$NON-NLS-1$

	if (context instanceof JavaContext) {
		JavaContext jc= (JavaContext) context;
		List<String> params= variable.getVariableType().getParams();
		if (params.size() > 0) {
			for (Iterator<String> iterator= params.iterator(); iterator.hasNext();) {
				String qualifiedMemberName= iterator.next();
				jc.addStaticImport(qualifiedMemberName);
			}
		}
	} else {
		super.resolve(variable, context);
	}
}
 
@Override
protected String resolve(TemplateContext context) {
	IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD);
	if (element == null)
		return null;

	IMethod method= (IMethod) element;

	try {
		String[] arguments= method.getParameterNames();
		StringBuffer buffer= new StringBuffer();

		for (int i= 0; i < arguments.length; i++) {
			if (i > 0)
				buffer.append(", "); //$NON-NLS-1$
			buffer.append(arguments[i]);
		}

		return buffer.toString();

	} catch (JavaModelException e) {
		return null;
	}
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (context instanceof JavaStatementPostfixContext && variable instanceof JavaVariable) {
		JavaStatementPostfixContext c = (JavaStatementPostfixContext) context;
		JavaVariable jv = (JavaVariable) variable;
		List<String> params = variable.getVariableType().getParams();
		
		if (!params.contains(HIDE_FLAG)) {
			jv.setValue(resolve(context));
		} else {
			jv.setValues(new String[] { "", resolve(context) }); // We hide the value from the output
		}
		
		jv.setParamType(c.getInnerExpressionTypeSignature());
		jv.setResolved(true);
		jv.setUnambiguous(true);
		return;
	}
	super.resolve(variable, context);
}
 
/**
 * 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();
	}
}
 
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;
}
 
源代码13 项目: goclipse   文件: JavaFormatter.java
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;
}
 
源代码14 项目: Pydev   文件: PyStringCodeCompletion.java
/**
 * @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
    }
}
 
源代码15 项目: goclipse   文件: CompilationUnitContextType.java
@Override
protected String resolve(TemplateContext context) {
	String selection= context.getVariable(GlobalTemplateVariables.SELECTION);
	if (selection == null)
		return "";
	return selection;
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext templateContext) {
	XtextTemplateContext castedContext = (XtextTemplateContext) templateContext;
	List<String> names = resolveValues(variable, castedContext);
	String[] bindings = names.toArray(new String[names.size()]);
	if (bindings.length != 0)
		variable.setValues(bindings);
	if (bindings.length > 1)
		variable.setUnambiguous(false);
	else
		variable.setUnambiguous(isUnambiguous(castedContext));
	variable.setResolved(true);
}
 
源代码17 项目: Pydev   文件: PyContextTypeVariables.java
@Override
protected String[] resolveAll(TemplateContext context) {
    String ret = this.callable.call((PyDocumentTemplateContext) context);
    if (ret == null) {
        ret = "";
    }
    return new String[] { ret };
}
 
protected TemplateContext[] createTemplateContexts(ContentAssistContext context) {
	TemplateContextType[] contextTypes = getContextTypes(context);
	if (contextTypes != null && contextTypes.length != 0) {
		TemplateContext[] result = new TemplateContext[contextTypes.length];
		for(int i = 0; i < contextTypes.length; i++) {
			result[i] = doCreateTemplateContext(contextTypes[i], context);
		}
		return result;
	}
	return null;
}
 
/**
 * 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);
    }
  }
}
 
/**
 * Adds template proposals for all checks which may be referenced in current catalog configuration. Only proposals for checks
 * which have not yet been configured are provided.
 *
 * @param templateContext
 *          the template context
 * @param context
 *          the context
 * @param acceptor
 *          the acceptor
 */
private void addConfiguredCheckTemplates(final TemplateContext templateContext, final ContentAssistContext context, final ITemplateAcceptor acceptor) { // NOPMD
  ConfiguredCatalog configuredCatalog = EcoreUtil2.getContainerOfType(context.getCurrentModel(), ConfiguredCatalog.class);
  Iterable<String> alreadyConfiguredCheckNames = Iterables.filter(Iterables.transform(configuredCatalog.getCheckConfigurations(), new Function<ConfiguredCheck, String>() {
    @Override
    public String apply(final ConfiguredCheck from) {
      if (from.getCheck() != null) {
        return from.getCheck().getName();
      }
      return null;
    }
  }), Predicates.notNull());
  final CheckCatalog catalog = configuredCatalog.getCatalog();
  for (final Check check : catalog.getAllChecks()) {
    // create a template on the fly
    final String checkName = check.getName();
    if (!Iterables.contains(alreadyConfiguredCheckNames, checkName)) {

      // check if referenced check has configurable parameters
      final StringJoiner paramsJoiner = new StringJoiner(", ", " (", ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      paramsJoiner.setEmptyValue(""); //$NON-NLS-1$
      for (final FormalParameter param : check.getFormalParameters()) {
        final String paramName = param.getName();
        final Object defaultValue = interpreter.evaluate(param.getRight()).getResult();

        final String valuePlaceholder = helper.createLiteralValuePattern(paramName, defaultValue);
        paramsJoiner.add(paramName + " = " + valuePlaceholder); //$NON-NLS-1$
      }

      final String severity = (catalog.isFinal() || check.isFinal()) ? "default " : "${default:Enum('SeverityKind')} "; //$NON-NLS-1$ //$NON-NLS-2$
      final String description = "Configures the check \"" + check.getLabel() + "\""; //$NON-NLS-1$ //$NON-NLS-2$
      final String contextTypeId = "com.avaloq.tools.ddk.checkcfg.CheckCfg.ConfiguredCheck." + checkName; //$NON-NLS-1$
      final String pattern = severity + qualifiedNameValueConverter.toString(checkName) + paramsJoiner + "${cursor}"; //$NON-NLS-1$

      Template t = new Template(checkName, description, contextTypeId, pattern, true);
      TemplateProposal tp = createProposal(t, templateContext, context, images.forConfiguredCheck(check.getDefaultSeverity()), getRelevance(t));
      acceptor.accept(tp);
    }
  }
}
 
源代码21 项目: statecharts   文件: SGenTemplateProposalProvider.java
@Override
protected void createTemplates(TemplateContext templateContext, ContentAssistContext context,
		ITemplateAcceptor acceptor) {
	super.createTemplates(templateContext, context, acceptor);

	String id = helper.getId(gaccess.getFeatureConfigurationRule());
	if (templateContext.getContextType().getId().equals(id)) {
		createFeatureConfigurationTemplates(templateContext, context, acceptor);
	}
}
 
源代码22 项目: statecharts   文件: SGenTemplateProposalProvider.java
private void createFeatureConfigurationTemplates(TemplateContext templateContext, ContentAssistContext context,
		ITemplateAcceptor acceptor) {
	GeneratorModel model = (GeneratorModel) EcoreUtil2.getRootContainer(context.getCurrentModel());

	Optional<IGeneratorDescriptor> generatorDescriptor = GeneratorExtensions
			.getGeneratorDescriptor(model.getGeneratorId());
	if (!generatorDescriptor.isPresent()) {
		return;
	}
	Iterable<ILibraryDescriptor> libraryDescriptor = LibraryExtensions
			.getLibraryDescriptors(generatorDescriptor.get().getLibraryIDs());

	for (ILibraryDescriptor desc : libraryDescriptor) {
		ResourceSet set = new ResourceSetImpl();
		Resource resource = set.getResource(desc.getURI(), true);
		FeatureTypeLibrary lib = (FeatureTypeLibrary) resource.getContents().get(0);
		EList<FeatureType> types = lib.getTypes();

		for (FeatureType featureType : types) {
			Template template = new Template(featureType.getName() + " feature",
					"Creates feature " + featureType.getName(), featureType.getName(),
					creator.createProposal(featureType,
							desc.createFeatureValueProvider(GenmodelActivator.getInstance()
									.getInjector(GenmodelActivator.ORG_YAKINDU_SCT_GENERATOR_GENMODEL_SGEN)),
							context.getCurrentModel()),
					false);
			TemplateProposal proposal = createProposal(template, templateContext, context, getImage(template),
					getRelevance(template));
			acceptor.accept(proposal);
		}
	}
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
    List params = variable.getVariableType().getParams();
    String[] bindings = new String[params.size()];
    for (int i = 0; i < params.size(); i++) {
        bindings[i] = params.get(i).toString();
    }
    if (bindings.length != 0)
        variable.setValues(bindings);
    variable.setResolved(true);
}
 
@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);
}
 
@SuppressWarnings("unchecked")
@Override
public void resolve(TemplateVariable variable, TemplateContext context)
{
	if (context instanceof DocumentSnippetTemplateContext)
	{
		DocumentSnippetTemplateContext documentSnippetTemplateContext = (DocumentSnippetTemplateContext) context;
		Template template = documentSnippetTemplateContext.getTemplate();
		if (template instanceof SnippetTemplate)
		{
			SnippetTemplate snippetTemplate = (SnippetTemplate) template;
			CommandElement snippet = snippetTemplate.getCommandElement();
			Map<String, String> environment = snippet.getEnvironment();
			String name = variable.getName();
			String value = environment.get(name);
			if (value == null)
			{
				if (!variable.getVariableType().getParams().isEmpty())
				{
					String[] values = (String[]) variable.getVariableType().getParams().toArray(new String[0]);
					variable.setValues(values);
					variable.setUnambiguous(false);
				}
				else
				{
					super.resolve(variable, context);
				}
			}
			else
			{
				variable.setValues(new String[] { value });
			}
			variable.setResolved(true);
		}
	}
}
 
@Override
protected ICompletionProposal createProposal(Template template, TemplateContext context, IRegion region,
		int relevance)
{
	if (template instanceof SnippetTemplate)
	{
		return new SnippetTemplateProposal(template, context, region, getImage(template), relevance);
	}
	return new CommandProposal(template, context, region, getImage(template), relevance);
}
 
@Override
protected TemplateContext createContext(ITextViewer viewer, IRegion region)
{
	TemplateContextType contextType = getContextType(viewer, region);
	if (contextType != null)
	{
		IDocument document = viewer.getDocument();
		return new DocumentSnippetTemplateContext(contextType, document, region.getOffset(), region.getLength());
	}
	return null;
}
 
@Override
protected String resolve(TemplateContext context) {
	IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD);
	if (element == null)
		return null;

	try {
		return Signature.toString(((IMethod) element).getReturnType());
	} catch (JavaModelException e) {
		return null;
	}
}
 
@Override
protected String resolve(TemplateContext context) {
	IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(fElementType);
	if (element instanceof IType)
		return JavaElementLabels.getElementLabel(element, JavaElementLabels.T_CONTAINER_QUALIFIED);
	return (element == null) ? null : element.getElementName();
}
 
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {

	variable.setUnambiguous(false);

	if (variable instanceof JavaVariable) {
		JavaContext jc= (JavaContext) context;
		JavaVariable jv= (JavaVariable) variable;

		List<String> params= variable.getVariableType().getParams();
		if (params.size() > 0) {
			fProposals= new String[params.size()];
			int i= 0;
			for (Iterator<String> iterator= params.iterator(); iterator.hasNext();) {
				String param= iterator.next();
				fProposals[i]= param;
				i++;
			}
			jv.setChoices(fProposals);
			jv.setCurrentChoice(fProposals[0]);

			jc.markAsUsed(jv.getDefaultValue());
		} else {
			fProposals= new String[] { variable.getDefaultValue() };
			super.resolve(variable, context);
			return;
		}
	} else
		super.resolve(variable, context);
}
 
 类所在包
 类方法
 同包方法