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

The following examples show how to use org.eclipse.jface.text.templates.TemplateProposal. 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: GamlEditor.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see msi.gama.lang.gaml.ui.editor.IGamlEditor#applyTemplate(org.eclipse.jface.text.templates.Template)
 */

public void applyTemplateAtTheEnd(final Template t) {

	try {
		final IDocument doc = getDocument();
		int offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
		doc.replace(offset, 0, "\n\n");
		offset += 2;
		final int length = 0;
		final Position pos = new Position(offset, length);
		final XtextTemplateContextType ct = new XtextTemplateContextType();
		final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
		final IRegion r = new Region(offset, length);
		final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
		tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
	} catch (final BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example #2
Source File: TemplatesFirstCompletionProposalComparator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings({"rawtypes", "unchecked"})
public int compare(final ICompletionProposal o1, final ICompletionProposal o2) {

  // Template sorting by relevance and then alphabetically by name
  if (o1 instanceof TemplateProposal && o2 instanceof TemplateProposal) {
    TemplateProposal t1 = (TemplateProposal) o1;
    TemplateProposal t2 = (TemplateProposal) o2;
    if (t1.getRelevance() == t2.getRelevance()) {
      return o1.getDisplayString().compareTo(o2.getDisplayString());
    }
    return ((Integer) t1.getRelevance()).compareTo(t1.getRelevance());
  }
  // Templates always first
  if (o1 instanceof TemplateProposal) {
    return -1;
  } else if (o2 instanceof TemplateProposal) {
    return 1;
  }
  // Fallback
  if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) {
    return ((Comparable) o1).compareTo(o2);
  }
  return o1.getDisplayString().compareTo(o2.getDisplayString());
}
 
Example #3
Source File: AbstractContentAssistUiTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Apply template proposal.
 *
 * @param templateProposal
 *          the template proposal, must not be {@code null}
 * @param offset
 *          offset in test file
 * @return the document text after application of the template proposal, never {@code null}
 */
private String applyTemplateProposal(final TemplateProposal templateProposal, final int offset) {
  // Apply proposal
  UiThreadDispatcher.dispatchAndWait(new Runnable() {
    @Override
    public void run() {
      Assert.assertNotNull(EDITOR_HAS_NO_VIEWER, getViewer());
      templateProposal.apply(getViewer(), ' ', 0, offset);
    }
  });

  waitForValidation();
  return getDocument().get();
}
 
Example #4
Source File: TemplateEngine.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
public List<ICompletionProposal> completeAndReturnResults(SourceOpContext sourceOpContext, IDocument document) 
		throws CommonException {
	complete(sourceOpContext, document);
	
	TemplateProposal[] templateProposals = getResults();
	return CollectionUtil.<ICompletionProposal>createArrayList(templateProposals);
}
 
Example #5
Source File: PythonModuleWizard.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Applies the template if one was specified.
 */
@Override
protected void afterEditorCreated(final IEditorPart openEditor) {
    if (!(openEditor instanceof PyEdit)) {
        return; //only works for PyEdit...
    }

    RunInUiThread.async(new Runnable() {

        @Override
        public void run() {
            PyEdit pyEdit = (PyEdit) openEditor;
            if (pyEdit.isDisposed()) {
                return;
            }
            TemplateSelectDialog dialog = new TemplateSelectDialog(Display.getCurrent().getActiveShell());
            dialog.open();
            TemplatePersistenceData selectedTemplate = dialog.getSelectedTemplate();
            if (selectedTemplate == null) {
                return; //no template selected, nothing to apply!
            }

            Template template = selectedTemplate.getTemplate();

            Region region = new Region(0, 0);
            PyDocumentTemplateContext context = PyDocumentTemplateContext.createContext(new PyContextType(),
                    pyEdit.getPySourceViewer(), region);

            TemplateProposal templateProposal = new TemplateProposal(template, context, region, null);
            templateProposal.apply(pyEdit.getPySourceViewer(), '\n', 0, 0);
        }
    });
}
 
Example #6
Source File: TddRefactorCompletion.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    if (edit != null) {
        //We have to reparse to make sure that we'll have an accurate AST.
        edit.getParser().reparseDocument();
    }
    TemplateProposal executed2 = getExecuted();
    if (executed2 != null) {
        executed2.apply(viewer, trigger, stateMask, 0);
        forceReparseInBaseEditorAnd();
    }
}
 
Example #7
Source File: TddRefactorCompletion.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Point getSelection(IDocument document) {
    TemplateProposal executed2 = getExecuted();
    if (executed2 != null) {
        return executed2.getSelection(document);
    }
    return null;
}
 
Example #8
Source File: CompletionProposalComparator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getRelevance(ICompletionProposal obj) {
	if (obj instanceof IJavaCompletionProposal) {
		IJavaCompletionProposal jcp= (IJavaCompletionProposal) obj;
		return jcp.getRelevance();
	} else if (obj instanceof TemplateProposal) {
		TemplateProposal tp= (TemplateProposal) obj;
		return tp.getRelevance();
	}
	// catch all
	return 0;
}
 
Example #9
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void applyTemplate(final Template t) {
	// TODO Create a specific context type (with GAML specific variables ??)
	final XtextTemplateContextType ct = new XtextTemplateContextType();
	final IDocument doc = getDocument();
	final ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
	final int offset = selection.getOffset();
	final int length = selection.getLength();
	final Position pos = new Position(offset, length);
	final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
	final IRegion r = new Region(offset, length);
	final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
	tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
}
 
Example #10
Source File: SGenTemplateProposalProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
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);
		}
	}
}
 
Example #11
Source File: CheckCfgTemplateProposalProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example #12
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 #13
Source File: ContentAssistXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private String applyProposal(ICompletionProposal proposal, IXtextDocument document) {
	return document.modify(
			state -> {
				state.setValidationDisabled(false);
				if (!(proposal instanceof TemplateProposal)) {
					proposal.apply(document);
				}
				return document.get();
			});
}
 
Example #14
Source File: DotTemplateProposalProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
protected TemplateProposal doCreateProposal(Template template,
		TemplateContext templateContext, ContentAssistContext context,
		Image image, int relevance) {
	EObject currentModel = context.getCurrentModel();

	if (isEdgeTemplate(template)) {
		template = replaceOpVariable(currentModel, template);
	}

	if (isHtmlLabelTemplate(template)) {
		if (currentModel instanceof Attribute) {
			ID attributeNameID = ((Attribute) currentModel).getName();
			if (attributeNameID != null) {
				String attributeName = attributeNameID.toValue();
				switch (attributeName) {
				case DotAttributes.HEADLABEL__E:
				case DotAttributes.LABEL__GCNE:
				case DotAttributes.TAILLABEL__E:
				case DotAttributes.XLABEL__NE:
					return super.doCreateProposal(template, templateContext,
							context, image, relevance);
				default:
					return null;
				}
			}
		} else {
			return null;
		}
	}

	return super.doCreateProposal(template, templateContext, context, image,
			relevance);
}
 
Example #15
Source File: ICompletionProposalComparator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns relevance of given proposal.
 * 
 * @param proposal either a {@link ConfigurableCompletionProposal} or a {@link TemplateProposal}
 * @return relevance (higher value indicates higher relevance) or <code>null</code>
 * @since 2.3
 */
protected Integer getRelevance(ICompletionProposal proposal) {
	if (proposal instanceof ConfigurableCompletionProposal) {
		return ((ConfigurableCompletionProposal) proposal).getPriority();
	} else if (proposal instanceof TemplateProposal) {
		return ((TemplateProposal) proposal).getRelevance();
	} else if (proposal instanceof QuickAssistCompletionProposal) {
		return ((QuickAssistCompletionProposal) proposal).getRelevance();
	}
	return null;
}
 
Example #16
Source File: ProposalXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private String applyProposal(ICompletionProposal proposal, IXtextDocument document) {
	return document.modify(
			new IUnitOfWork<String, XtextResource>() {
				@Override
				public String exec(XtextResource state) throws Exception {
					state.setValidationDisabled(false);
					if (!(proposal instanceof TemplateProposal)) {
						proposal.apply(document);
					}
					return document.get();
				}
			});
}
 
Example #17
Source File: AbstractTemplateProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected TemplateProposal doCreateProposal(Template template, TemplateContext templateContext,
		ContentAssistContext context, Image image, int relevance) {
	return new XtextTemplateProposal(template, templateContext, context.getReplaceRegion(), image, relevance);
}
 
Example #18
Source File: AbstractTemplateProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected TemplateProposal createProposal(Template template, TemplateContext templateContext,
		ContentAssistContext context, Image image, int relevance) {
	if (!validate(template, context))
		return null;
	return doCreateProposal(template, templateContext, context, image, relevance);
}
 
Example #19
Source File: AbstractTemplateProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void accept(TemplateProposal template) {
	if (template != null)
		super.accept(template);
}
 
Example #20
Source File: CompletionProposalComputer.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void accept(TemplateProposal template) {
	if (template == null)
		throw new NullPointerException("template may not be null");
	proposals.add(template);
}
 
Example #21
Source File: ITemplateAcceptor.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void accept(TemplateProposal template) {
	delegate.accept(template);
}
 
Example #22
Source File: TemplateEngine.java    From goclipse with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the array of matching templates.
 *
 * @return the template proposals
 */
public TemplateProposal[] getResults() {
	return fProposals.toArray(new TemplateProposal[fProposals.size()]);
}
 
Example #23
Source File: ITemplateAcceptor.java    From xtext-eclipse with Eclipse Public License 2.0 votes vote down vote up
void accept(TemplateProposal template);