/** {@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()); }
/** * @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(); } }
private ICompletionProposal createProposal(PySelection ps, ImageCache imageCache, PyEdit 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) { TemplateProposal proposal = new TemplateProposal(t, context, region, imageCache.get(UIConstants.COMPLETION_TEMPLATE), 5) { @Override public String getAdditionalProposalInfo() { return startIndent + super.getAdditionalProposalInfo(); } }; return proposal; } else { //In tests return new CompletionProposal(comp, region.getOffset(), region.getLength(), 0); } }
private String applyProposal(ICompletionProposal proposal, IXtextDocument document) { return document.modify( state -> { state.setValidationDisabled(false); if (!(proposal instanceof TemplateProposal)) { proposal.apply(document); } return document.get(); }); }
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(); } }); }
/** * 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(); }
/** * 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; }
private void createFeatureConfigurationTemplates(TemplateContext templateContext, ContentAssistContext context, ITemplateAcceptor acceptor) { GeneratorModel model = (GeneratorModel) EcoreUtil2.getRootContainer(context.getCurrentModel()); IGeneratorDescriptor generatorDescriptor = GeneratorExtensions.getGeneratorDescriptor(model.getGeneratorId()); Iterable<ILibraryDescriptor> libraryDescriptor = LibraryExtensions .getLibraryDescriptors(generatorDescriptor.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(SGenActivator.getInstance() .getInjector(SGenActivator.ORG_YAKINDU_SCT_GENERATOR_GENMODEL_SGEN)), context.getCurrentModel()), false); TemplateProposal proposal = createProposal(template, templateContext, context, getImage(template), getRelevance(template)); acceptor.accept(proposal); } } }
@Override protected ICompletionProposal createProposal(Template template, TemplateContext context, IRegion region, int relevance) { TemplateProposal proposal = new BfTemplateProposal(template, context, region, getImage(template), relevance); proposal.setInformationControlCreator(informationControlCreator); return proposal; }
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); }
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; }
@Override public Point getSelection(IDocument document) { TemplateProposal executed2 = getExecuted(); if (executed2 != null) { return executed2.getSelection(document); } return null; }
@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(); } }
/** * 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 = PyTemplateCompletionProcessor.createContext(new PyContextType(), pyEdit.getPySourceViewer(), region); TemplateProposal templateProposal = new TemplateProposal(template, context, region, null); templateProposal.apply(pyEdit.getPySourceViewer(), '\n', 0, 0); } }); }
protected Integer _getRelevance(final TemplateProposal proposal) { Integer _xifexpression = null; String _displayString = proposal.getDisplayString(); boolean _startsWith = _displayString.startsWith("template: "); if (_startsWith) { _xifexpression = TemplatePreferringCompletionProposalProvider.PREMIUM_RELEVANCE; } else { _xifexpression = TemplatePreferringCompletionProposalProvider.HIGH_RELEVANCE; } return _xifexpression; }
public Integer getRelevance(final Object proposal) { if (proposal instanceof TemplateProposal) { return _getRelevance((TemplateProposal)proposal); } else if (proposal instanceof ConfigurableCompletionProposal) { return _getRelevance((ConfigurableCompletionProposal)proposal); } else if (proposal instanceof QuickAssistCompletionProposal) { return _getRelevance((QuickAssistCompletionProposal)proposal); } else if (proposal != null) { return _getRelevance(proposal); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(proposal).toString()); } }
public List<ICompletionProposal> completeAndReturnResults(SourceOpContext sourceOpContext, IDocument document) throws CommonException { complete(sourceOpContext, document); TemplateProposal[] templateProposals = getResults(); return CollectionUtil.<ICompletionProposal>createArrayList(templateProposals); }
/** * 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"; final String templateDescription = "configures all missing catalogs"; 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()); } builder.append("catalog ").append(description.getQualifiedName()).append(" {").append(Strings.newLine()); for (Check check : catalog.getAllChecks()) { builder.append(" default ").append(check.getName()).append(Strings.newLine()); } // CHECKSTYLE:OFF builder.append("}"); builder.append(Strings.newLine()); // CHECKSTYLE:ON } } if (builder.length() > 0) { builder.append("${cursor}"); 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 String paramString = ""; //$NON-NLS-1$ if (!check.getFormalParameters().isEmpty()) { StringBuilder params = new StringBuilder("("); //$NON-NLS-1$ for (final FormalParameter p : check.getFormalParameters()) { final String paramName = p.getName(); final String defaultValue = String.valueOf(interpreter.evaluate(p.getRight()).getResult()); params.append(paramName).append(" = ").append("${").append(defaultValue).append('}'); //$NON-NLS-1$ //$NON-NLS-2$ params.append(", "); //$NON-NLS-1$ } if (params.length() > 2) { paramString = params.substring(0, params.length() - 2) + ')'; } } 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 + checkName + (paramString.length() == 0 ? "${cursor}" : " " + paramString + "${cursor}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Template t = new Template(checkName, description, contextTypeId, pattern, true); TemplateProposal tp = createProposal(t, templateContext, context, images.forConfiguredCheck(check.getDefaultSeverity()), getRelevance(t)); acceptor.accept(tp); } } }
public int compare(ICompletionProposal o1, ICompletionProposal o2) { int r1= o1 instanceof TemplateProposal ? ((TemplateProposal) o1).getRelevance() : 0; int r2= o2 instanceof TemplateProposal ? ((TemplateProposal) o2).getRelevance() : 0; return r2 - r1; }
public void accept(TemplateProposal template) { delegate.accept(template); }
public void accept(TemplateProposal template) { if (template == null) throw new NullPointerException("template may not be null"); proposals.add(template); }
@Override public void accept(TemplateProposal template) { if (template != null) super.accept(template); }
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); }
protected TemplateProposal doCreateProposal(Template template, TemplateContext templateContext, ContentAssistContext context, Image image, int relevance) { return new XtextTemplateProposal(template, templateContext, context.getReplaceRegion(), image, relevance); }
protected ICompletionProposal createProposal(PySelection pySelection, String source, Tuple<Integer, String> offsetAndIndent, boolean requireEmptyLines, Pass replacePassStatement) { int offset; int len; String indent = offsetAndIndent.o2; if (replacePassStatement == null) { len = 0; offset = offsetAndIndent.o1; if (requireEmptyLines) { int checkLine = pySelection.getLineOfOffset(offset); int lineOffset = pySelection.getLineOffset(checkLine); //Make sure we have 2 spaces from the last thing written. if (lineOffset == offset) { //it'll be added to the start of the line, so, we have to analyze the previous line to know if we'll need //to new lines at the start. checkLine--; } if (checkLine >= 0) { //It'll be added to the current line, so, check the current line and the previous line to know about spaces. String line = pySelection.getLine(checkLine); if (line.trim().length() >= 1) { source = "\n\n" + source; } else if (checkLine > 1) { line = pySelection.getLine(checkLine - 1); if (line.trim().length() > 0) { source = "\n" + source; } } } //If we have a '\n', all is OK (all contents after a \n will be indented) if (!source.startsWith("\n")) { try { //Ok, it doesn't start with a \n, that means we have to check the line indentation where it'll //be added and make sure things are correct (eventually adding a new line or just fixing the indent). String lineContentsToCursor = pySelection.getLineContentsToCursor(offset); if (lineContentsToCursor.length() > 0) { source = "\n" + source; } else { source = indent + source; } } catch (BadLocationException e) { source = "\n" + source; } } } } else { offset = pySelection.getAbsoluteCursorOffset(replacePassStatement.beginLine - 1, replacePassStatement.beginColumn - 1); len = 4; //pass.len if (requireEmptyLines) { source = "\n\n" + source; } } if (targetEditor != null) { String creationStr = getCreationStr(); Region region = new Region(offset, len); //Note: was using new PyContextType(), but when we had something as ${user} it //would end up replacing it with the actual name of the user, which is not what //we want! TemplateContextType contextType = new TemplateContextType(); contextType.addResolver(new GlobalTemplateVariables.Cursor()); //We do want the cursor thought. PyDocumentTemplateContext context = PyTemplateCompletionProcessor.createContext(contextType, targetEditor.getPySourceViewer(), region, indent); Template template = new Template("Create " + creationStr, "Create " + creationStr, "", source, true); TemplateProposal templateProposal = new TemplateProposal(template, context, region, null); return templateProposal; } else { //This should only happen in tests. source = StringUtils.indentTo(source, indent, false); return new CompletionProposal(source, offset, len, 0); } }
/** * @param ret OUT: this is where the completions are stored */ private void fillWithEpydocFields(ITextViewer viewer, CompletionRequest request, ArrayList<ICompletionProposal> ret) { try { Region region = new Region(request.documentOffset - request.qlen, request.qlen); Image image = PyCodeCompletionImages.getImageForType(IToken.TYPE_EPYDOC); TemplateContext context = createContext(viewer, 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(new TemplateProposal(t, context, region, image, 5) { @Override public String getDisplayString() { if (SharedCorePlugin.inTestMode()) { return this.getPrefixCompletionText(null, 0).toString(); } else { return super.getDisplayString(); } } }); } i += 2; } } } catch (BadLocationException e) { //just ignore it } }
/** * @see org.python.pydev.editor.correctionassist.heuristics.IAssistProps#getProps(org.python.pydev.core.docutils.PySelection, * org.python.pydev.shared_ui.ImageCache) */ @Override public List<ICompletionProposal> getProps(PySelection ps, ImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset) throws BadLocationException { ArrayList<ICompletionProposal> l = new ArrayList<ICompletionProposal>(); String curSelection = ps.getSelectedText(); if (curSelection == null) { return l; } curSelection = new String(curSelection); boolean endsWithLineDelim = false; int unchangedLength = curSelection.length(); if (curSelection.substring(unchangedLength-1, unchangedLength).matches("\\r|\\n") || curSelection.substring(unchangedLength-2, unchangedLength).matches("\\r\\n")) { endsWithLineDelim = true; } PercentToBraceConverter ptbc = new PercentToBraceConverter(curSelection); String replacementString = ptbc.convert(); if (endsWithLineDelim) { replacementString += ps.getEndLineDelim(); } int lenConverted = ptbc.getLength(); int replacementOffset = offset; int replacementLength = unchangedLength; int cursorPos = replacementOffset + lenConverted; if (DEBUG) { String sep = System.getProperty("line.separator"); System.out.format(sep + "Replacement String: %s" + sep + "Replacement Offset: %d" + sep + "Replacement Length: %d" + sep + "Cursor Position: %d", replacementString, replacementOffset, replacementLength, cursorPos); } IRegion region = ps.getRegion(); TemplateContext context = createContext(edit.getPySourceViewer(), region, ps.getDoc()); Template t = new Template("Convert", "% to .format()", "", replacementString, false); l.add(new TemplateProposal(t, context, region, imageCache.get(UIConstants.COMPLETION_TEMPLATE), 5)); return l; }
public int compare(Object o1, Object o2) { return ((TemplateProposal) o2).getRelevance() - ((TemplateProposal) o1).getRelevance(); }
protected ICompletionProposal createRuleTemplate(IDocument document, int offset) { TemplateContext context = new DocumentTemplateContext(new TemplateContextType(), document, offset, 0); TemplateProposal proposal = new TemplateProposal(TEMPLATE_RULE, context, new Region(offset, 0), BytemanEditorPluginImages.IMG_OBJS_TEMPLATE); return proposal; }
/** * Returns the array of matching templates. * * @return the template proposals */ public TemplateProposal[] getResults() { return fProposals.toArray(new TemplateProposal[fProposals.size()]); }
void accept(TemplateProposal template);