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

The following examples show how to use org.eclipse.jface.text.templates.TemplateContext. 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: TabStopVariableResolver.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@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());
	}
}
 
Example #2
Source File: AbstractTemplateProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #3
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: JSONProposalFactory.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #5
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 #6
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: InnerExpressionResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: CompilationUnitContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
	}
}
 
Example #9
Source File: CheckCfgTemplateProposalProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@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)));
    }
  }
}
 
Example #10
Source File: StaticImportResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: TypeResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #12
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 #13
Source File: AssistSurroundWith.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
    }
}
 
Example #14
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (variable instanceof MultiVariable) {
		JavaContext jc= (JavaContext) context;
		MultiVariable mv= (MultiVariable) variable;

		Variable[] iterables= getVariablesInContextScope(jc);
		if (iterables.length > 0) {

			for (int i= 0; i < iterables.length; i++)
				mv.setChoices(iterables[i], iterables[i].getMemberTypeNames());

			TemplateVariable master= jc.getTemplateVariable(fMasterName);
			if (master instanceof MultiVariable) {
				final MultiVariable masterMv= (MultiVariable) master;
				jc.addDependency(masterMv, mv);
				mv.setKey(masterMv.getCurrentChoice());
			}

			if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
				variable.setUnambiguous(false);
			else
				variable.setUnambiguous(isUnambiguous(context));

			return;
		}

	}

	super.resolve(variable, context);
}
 
Example #15
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected String[] resolveAll(TemplateContext context) {
       JavaContext jc= (JavaContext) context;
       Variable[] iterables= getVariables(jc);
       String[] names= new String[iterables.length];
       for (int i= 0; i < iterables.length; i++)
		names[i]= iterables[i].getName();
       if (names.length > 0)
       	jc.markAsUsed(names[0]);
	return names;
   }
 
Example #16
Source File: LinkResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: OuterExpressionResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected String resolve(TemplateContext context) {
	if (!(context instanceof JavaStatementPostfixContext)) 
		return "";
	
	JavaStatementPostfixContext c = (JavaStatementPostfixContext) context;
	
	return c.getOuterExpression();
}
 
Example #18
Source File: ExceptionVariableNameResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected String[] resolveAll(TemplateContext context) {
	if (context instanceof JavaContext) {
		JavaContext jc= (JavaContext) context;
		IJavaProject javaProject= jc.getJavaProject();
		String exceptionVariableName= StubUtility.getExceptionVariableName(javaProject);
		return StubUtility.getLocalNameSuggestions(jc.getJavaProject(), exceptionVariableName, 0, jc.computeExcludes());
	}
	return new String[0];
}
 
Example #19
Source File: CodeTemplateContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected String resolve(TemplateContext context) {
	String todoTaskTag= StubUtility.getTodoTaskTag(((CodeTemplateContext) context).getJavaProject());
	if (todoTaskTag == null)
		return "XXX"; //$NON-NLS-1$

	return todoTaskTag;
}
 
Example #20
Source File: CompilationUnitContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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();
}
 
Example #21
Source File: JavaDocContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected String resolve(TemplateContext context) {
	String selection= context.getVariable(org.eclipse.jface.text.templates.GlobalTemplateVariables.SELECTION);
	if (selection == null)
		return ""; //$NON-NLS-1$
	return selection;
}
 
Example #22
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 #23
Source File: CompilationUnitContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
	}
}
 
Example #24
Source File: TemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a template proposal with a template and its context.
 *
 * @param template  the template
 * @param context   the context in which the template was requested.
 * @param region	the region this proposal is applied to
 * @param image     the icon of the proposal.
 */
public TemplateProposal(Template template, TemplateContext context, IRegion region, Image image) {
	Assert.isNotNull(template);
	Assert.isNotNull(context);
	Assert.isNotNull(region);

	fTemplate= template;
	fContext= context;
	fImage= image;
	fRegion= region;

	fDisplayString= null;

	fRelevance= computeRelevance();
}
 
Example #25
Source File: QuickTemplateProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean canEvaluate(TemplateContext context, Template template) {
	String contextId= context.getContextType().getId();
	if (JavaDocContextType.ID.equals(contextId)) {
		if (!template.matches("", contextId) || template.getPattern().indexOf($_LINE_SELECTION) == -1 && template.getPattern().indexOf($_WORD_SELECTION) == -1) //$NON-NLS-1$
			return false;
	} else {
		if (template.matches("", JavaDocContextType.ID) || template.getPattern().indexOf($_LINE_SELECTION) == -1) //$NON-NLS-1$
			return false;
	}
	TemplateContextType contextType= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(template.getContextTypeId());
	return contextType instanceof CompilationUnitContextType;
}
 
Example #26
Source File: InnerExpressionTypeResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected String resolve(TemplateContext context) {
	if (!(context instanceof JavaStatementPostfixContext)) 
		return "";
	
	JavaStatementPostfixContext c = (JavaStatementPostfixContext) context;
	
	return ((JavaStatementPostfixContext)context).getInnerExpressionTypeSignature();
}
 
Example #27
Source File: SnippetsCompletionProcessor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #28
Source File: SnippetsCompletionProcessor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: EnvironmentVariableVariableResolver.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@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);
		}
	}
}
 
Example #30
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (variable instanceof MultiVariable) {
		JavaContext jc= (JavaContext) context;
		MultiVariable mv= (MultiVariable) variable;

        Variable[] iterables= getLocalVariables(jc);
		if (iterables.length > 0) {
			for (int i= 0; i < iterables.length; i++) {
				String[] elements= jc.suggestVariableNames(iterables[i].getMemberTypeNames()[0]);
				mv.setChoices(iterables[i], elements);
			}


			TemplateVariable master= jc.getTemplateVariable(fMasterName);
			if (master instanceof MultiVariable) {
				final MultiVariable masterMv= (MultiVariable) master;
				jc.addDependency(masterMv, mv);
				mv.setKey(masterMv.getCurrentChoice());
			}
			jc.markAsUsed(mv.getDefaultValue());

			if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
				variable.setUnambiguous(false);
			else
				variable.setUnambiguous(isUnambiguous(context));

			return;
		}

	}
	super.resolve(variable, context);
}