Search in sources :

Example 21 with ConfigurableCompletionProposal

use of org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal in project xtext-eclipse by eclipse.

the class ProjectionAwareProposalAcceptor method accept.

@Override
public void accept(ICompletionProposal proposal) {
    if (proposal != null) {
        ConfigurableCompletionProposal configurableProposal = (ConfigurableCompletionProposal) proposal;
        configurableProposal.setSelectionStart(evaluatedTemplate.getOriginalOffset(configurableProposal.getSelectionStart()));
        configurableProposal.setReplacementOffset(evaluatedTemplate.getOriginalOffset(configurableProposal.getReplacementOffset()));
        acceptor.accept(proposal);
    }
}
Also used : ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal)

Example 22 with ConfigurableCompletionProposal

use of org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal in project xtext-eclipse by eclipse.

the class CrossReferenceProposalTest method testBug356185.

@Test
public void testBug356185() throws Exception {
    final String content = "Foo {}";
    XtextResourceSet rs = new XtextResourceSet() {

        @Override
        protected void demandLoad(Resource resource) throws IOException {
            resource.load(new StringInputStream(content), null);
        }
    };
    rs.setClasspathURIContext(getClass());
    XtextResource resource1 = (XtextResource) rs.createResource(URI.createURI("test1." + getCurrentFileExtension()));
    resource1.load(new StringInputStream(content), null);
    Model model = (Model) resource1.getContents().get(0);
    URI classToShowURI = EcoreUtil.getURI(model.getElements().get(0));
    resource1.unload();
    ClassImpl classToShow = (ClassImpl) CrossReferenceProposalTestFactory.eINSTANCE.createClass();
    classToShow.eSetProxyURI(classToShowURI);
    ResourceSet resourceSet = resource1.getResourceSet();
    XtextResource resource2 = (XtextResource) resourceSet.createResource(URI.createURI("test." + getCurrentFileExtension()));
    resource2.load(new StringInputStream("Foo <- Bar {}"), null);
    ContentAssistContext.Builder builder = get(ContentAssistContext.Builder.class);
    builder.setResource(resource2);
    builder.setReplaceRegion(new Region(0, 0));
    model = (Model) resource2.getContents().get(0);
    Class contextClass = model.getElements().get(0);
    ICompositeNode node = NodeModelUtils.getNode(contextClass);
    builder.setCurrentNode(node);
    builder.setMatcher(new PrefixMatcher() {

        @Override
        public boolean isCandidateMatchingPrefix(String name, String prefix) {
            return true;
        }
    });
    ContentAssistContext context = builder.toContext();
    ContentProposalProvider proposalProvider = get(ContentProposalProvider.class);
    proposalProvider.setConflictHelper(new IProposalConflictHelper() {

        @Override
        public boolean existsConflict(String proposal, ContentAssistContext context) {
            return false;
        }
    });
    Function<IEObjectDescription, ICompletionProposal> proposalFactory = proposalProvider.getProposalFactory(context);
    ConfigurableCompletionProposal proposal = (ConfigurableCompletionProposal) proposalFactory.apply(new EObjectDescription(QualifiedName.create("Foo"), classToShow, null));
    assertTrue(classToShow.eIsProxy());
    Object additionalProposalInfo = proposal.getAdditionalProposalInfo(new NullProgressMonitor());
    assertNotNull(additionalProposalInfo);
}
Also used : EObjectDescription(org.eclipse.xtext.resource.EObjectDescription) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) ClassImpl(org.eclipse.xtext.ui.tests.editor.contentassist.crossReferenceProposalTest.impl.ClassImpl) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) XtextResource(org.eclipse.xtext.resource.XtextResource) URI(org.eclipse.emf.common.util.URI) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) IProposalConflictHelper(org.eclipse.xtext.ui.editor.contentassist.IProposalConflictHelper) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) StringInputStream(org.eclipse.xtext.util.StringInputStream) ContentAssistContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext) Model(org.eclipse.xtext.ui.tests.editor.contentassist.crossReferenceProposalTest.Model) Region(org.eclipse.jface.text.Region) EClass(org.eclipse.emf.ecore.EClass) Class(org.eclipse.xtext.ui.tests.editor.contentassist.crossReferenceProposalTest.Class) EObject(org.eclipse.emf.ecore.EObject) Test(org.junit.Test)

Example 23 with ConfigurableCompletionProposal

use of org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal in project xtext-eclipse by eclipse.

the class TerminalsProposalProvider method createIntProposal.

private void createIntProposal(ContentAssistContext context, ICompletionProposalAcceptor acceptor, RuleCall ruleCall, String feature, int i) {
    String proposalText = getValueConverter().toString(i, ruleCall.getRule().getName());
    String displayText = proposalText + " - " + ruleCall.getRule().getName();
    if (feature != null)
        displayText = proposalText + " - " + feature;
    ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, context);
    if (proposal instanceof ConfigurableCompletionProposal) {
        ConfigurableCompletionProposal configurable = (ConfigurableCompletionProposal) proposal;
        configurable.setSelectionStart(configurable.getReplacementOffset());
        configurable.setSelectionLength(proposalText.length());
        configurable.setAutoInsertable(false);
        configurable.setSimpleLinkedMode(context.getViewer(), '\t', ' ');
    }
    acceptor.accept(proposal);
}
Also used : ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal)

Example 24 with ConfigurableCompletionProposal

use of org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal in project xtext-eclipse by eclipse.

the class XtextProposalProvider method createOverrideProposal.

protected void createOverrideProposal(final AbstractRule overrideMe, final Grammar grammar, final ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
    StringBuilder proposal = new StringBuilder();
    String ruleKind = "parser rule";
    if (overrideMe instanceof TerminalRule) {
        proposal.append("terminal ");
        if (((TerminalRule) overrideMe).isFragment()) {
            proposal.append("fragment ");
            ruleKind = "terminal fragment";
        } else {
            ruleKind = "terminal rule";
        }
    }
    if (overrideMe instanceof EnumRule) {
        proposal.append("enum ");
        ruleKind = "enum rule";
    }
    if (overrideMe instanceof ParserRule && ((ParserRule) overrideMe).isFragment()) {
        proposal.append("fragment ");
        ruleKind = "parser fragment";
    }
    proposal.append(overrideMe.getName());
    String paramList = getParamList(overrideMe);
    proposal.append(paramList);
    boolean foundPack = appendReturnType(overrideMe, grammar, proposal);
    proposal.append(":\n\t");
    final int selectionStart = proposal.length();
    proposal.append("super");
    proposal.append(paramList);
    final int selectionEnd = proposal.length();
    proposal.append("\n;");
    ConfigurableCompletionProposal completionProposal = (ConfigurableCompletionProposal) createCompletionProposal(proposal.toString(), overrideMe.getName() + " - override " + ruleKind + " " + overrideMe.getName() + paramList, getImage(overrideMe), context.copy().setMatcher(new PrefixMatcher() {

        @Override
        public boolean isCandidateMatchingPrefix(String name, String prefix) {
            // match only against rulename - ignore rule type
            return context.getMatcher().isCandidateMatchingPrefix(overrideMe.getName(), prefix);
        }
    }).toContext());
    if (completionProposal != null) {
        completionProposal.setSelectionStart(selectionStart + completionProposal.getReplacementOffset());
        completionProposal.setSelectionLength(selectionEnd - selectionStart);
        completionProposal.setCursorPosition(selectionEnd);
        completionProposal.setSimpleLinkedMode(context.getViewer(), '\t', '\n', '\r');
        if (!foundPack) {
            // we need to add a new import statement to the grammar
            completionProposal.setTextApplier(new ConfigurableCompletionProposal.IReplacementTextApplier() {

                @Override
                public void apply(IDocument document, ConfigurableCompletionProposal proposal) throws BadLocationException {
                    // compute import statement's offset
                    int offset = 0;
                    boolean startWithLB = true;
                    if (grammar.getMetamodelDeclarations().isEmpty()) {
                        startWithLB = false;
                        if (grammar.getRules().isEmpty()) {
                            offset = document.getLength();
                        } else {
                            ICompositeNode node = NodeModelUtils.getNode(grammar.getRules().get(0));
                            if (node != null)
                                offset = node.getOffset();
                        }
                    } else {
                        ICompositeNode node = NodeModelUtils.getNode(grammar.getMetamodelDeclarations().get(grammar.getMetamodelDeclarations().size() - 1));
                        if (node != null)
                            offset = node.getEndOffset();
                    }
                    offset = Math.min(proposal.getReplacementOffset(), offset);
                    // apply proposal
                    String replacementString = proposal.getReplacementString();
                    proposal.setCursorPosition(replacementString.length());
                    document.replace(proposal.getReplacementOffset(), proposal.getReplacementLength(), replacementString);
                    // add import statement
                    EPackage classifierPackage = overrideMe.getType().getClassifier().getEPackage();
                    StringBuilder insertMe = new StringBuilder("import ").append(getValueConverter().toString(classifierPackage.getNsURI(), grammarAccess.getSTRINGRule().getName()));
                    if (startWithLB)
                        insertMe.insert(0, '\n');
                    insertMe.append(" as ").append(getValueConverter().toString(classifierPackage.getName(), grammarAccess.getValidIDRule().getName()));
                    insertMe.append('\n');
                    document.replace(offset, 0, insertMe.toString());
                    proposal.setCursorPosition(proposal.getCursorPosition() + insertMe.length() - 3);
                    proposal.setSelectionStart(selectionStart + proposal.getReplacementOffset() + insertMe.length());
                    proposal.setCursorPosition(selectionEnd + insertMe.length());
                }
            });
        }
        acceptor.accept(completionProposal);
    }
}
Also used : PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) FQNPrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.FQNPrefixMatcher) ParserRule(org.eclipse.xtext.ParserRule) StyledString(org.eclipse.jface.viewers.StyledString) EPackage(org.eclipse.emf.ecore.EPackage) EnumRule(org.eclipse.xtext.EnumRule) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) TerminalRule(org.eclipse.xtext.TerminalRule) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 25 with ConfigurableCompletionProposal

use of org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal in project xtext-eclipse by eclipse.

the class JdtTypesProposalProvider method searchAndCreateProposals.

protected void searchAndCreateProposals(IJavaSearchScope scope, final ICompletionProposalFactory proposalFactory, ContentAssistContext context, EReference typeReference, final Filter filter, final IValueConverter<String> valueConverter, final ICompletionProposalAcceptor acceptor) throws JavaModelException {
    String prefix = context.getPrefix();
    List<String> split = Strings.split(prefix, '.');
    char[] typeName = null;
    char[] packageName = null;
    if (prefix.length() > 0 && !split.isEmpty()) {
        CharMatcher dotMatcher = CharMatcher.is('.');
        if (Character.isUpperCase(split.get(split.size() - 1).charAt(0))) {
            typeName = split.get(split.size() - 1).toCharArray();
            if (split.size() > 1)
                packageName = ("*" + dotMatcher.replaceFrom(prefix.substring(0, prefix.length() - (typeName.length + 1)), "*.") + "*").toCharArray();
        } else {
            if (prefix.endsWith("."))
                prefix = prefix.substring(0, prefix.length() - 1);
            packageName = ("*" + dotMatcher.replaceFrom(prefix, "*.") + "*").toCharArray();
        }
    }
    IScope typeScope = null;
    if (context.getCurrentModel() != null) {
        typeScope = scopeProvider.getScope(context.getCurrentModel(), typeReference);
    }
    final IReplacementTextApplier textApplier = createTextApplier(context, typeScope, qualifiedNameConverter, valueConverter);
    final ICompletionProposalAcceptor scopeAware = textApplier != null ? new ICompletionProposalAcceptor.Delegate(acceptor) {

        @Override
        public void accept(ICompletionProposal proposal) {
            if (proposal instanceof ConfigurableCompletionProposal) {
                ((ConfigurableCompletionProposal) proposal).setTextApplier(textApplier);
            }
            super.accept(proposal);
        }
    } : acceptor;
    Builder contextBuilder = context.copy();
    final PrefixMatcher original = context.getMatcher();
    contextBuilder.setMatcher(new PrefixMatcher() {

        @Override
        public boolean isCandidateMatchingPrefix(String name, String prefix) {
            if (original.isCandidateMatchingPrefix(name, prefix))
                return true;
            String nameWithoutDollars = name.replace('$', '.');
            String prefixWithoutDollars = prefix.replace('$', '.');
            final boolean nameOrPrefixHasDollars = (nameWithoutDollars != name) || (prefixWithoutDollars != prefix);
            if (nameOrPrefixHasDollars && original.isCandidateMatchingPrefix(nameWithoutDollars, prefixWithoutDollars))
                return true;
            String sub = nameWithoutDollars;
            int delimiter = sub.indexOf('.');
            while (delimiter != -1) {
                sub = sub.substring(delimiter + 1);
                delimiter = sub.indexOf('.');
                if (delimiter == -1 || prefixWithoutDollars.length() > 0 && Character.isLowerCase(prefixWithoutDollars.charAt(0))) {
                    if (original.isCandidateMatchingPrefix(sub, prefixWithoutDollars))
                        return true;
                }
            }
            return false;
        }
    });
    final ContentAssistContext myContext = contextBuilder.toContext();
    final IJvmTypeProvider jvmTypeProvider = jdtTypeProviderFactory.findOrCreateTypeProvider(context.getResource().getResourceSet());
    final Set<String> filteredTypeNames = getDirtyTypeNames();
    final Filter dirtyTypenameFilter = new ITypesProposalProvider.Filter() {

        @Override
        public boolean accept(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
            if (path == null || path.endsWith(".class") || path.endsWith(".java")) {
                // Java index match
                String identifier = getIdentifier(packageName, simpleTypeName, enclosingTypeNames);
                if (filteredTypeNames.contains(identifier)) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public int getSearchFor() {
            return filter.getSearchFor();
        }
    };
    BasicSearchEngine searchEngine = new BasicSearchEngine();
    searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName, SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CAMELCASE_MATCH, filter.getSearchFor(), scope, new IRestrictedAccessTypeRequestor() {

        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
            if (dirtyTypenameFilter.accept(modifiers, packageName, simpleTypeName, enclosingTypeNames, path) && filter.accept(modifiers, packageName, simpleTypeName, enclosingTypeNames, path) && (!checkAccessRestriction() || (access == null || access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter()))) {
                StringBuilder fqName = new StringBuilder(packageName.length + simpleTypeName.length + 1);
                if (packageName.length != 0) {
                    fqName.append(packageName);
                    fqName.append('.');
                }
                for (char[] enclosingType : enclosingTypeNames) {
                    /*
								 * the JDT index sometimes yields enclosingTypeNames in the form
								 * char[][] { { Outer$Middle } }
								 * rather than
								 * char[][] { { Outer }, { Middle } }
								 * thus we create the fqName as the binary name and post process the proposal later on
								 */
                    fqName.append(enclosingType);
                    fqName.append('$');
                }
                fqName.append(simpleTypeName);
                String fqNameAsString = fqName.toString();
                createTypeProposal(fqNameAsString, modifiers, enclosingTypeNames.length > 0, proposalFactory, myContext, scopeAware, jvmTypeProvider, valueConverter);
            }
        }
    }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor() {

        @Override
        public boolean isCanceled() {
            return !acceptor.canAcceptMoreProposals();
        }
    });
    if (acceptor.canAcceptMoreProposals()) {
        Iterable<IEObjectDescription> allDirtyTypes = dirtyStateManager.getExportedObjectsByType(TypesPackage.Literals.JVM_TYPE);
        for (IEObjectDescription description : allDirtyTypes) {
            QualifiedName qualifiedName = description.getQualifiedName();
            final int modifiers = getDirtyStateModifiers(context, description);
            if (filter.accept(modifiers, qualifiedName.skipLast(1).toString().toCharArray(), qualifiedName.getLastSegment().toCharArray(), new char[0][0], description.getEObjectURI().toPlatformString(true))) {
                String fqName = description.getQualifiedName().toString();
                createTypeProposal(fqName, modifiers, fqName.indexOf('$') > 0, proposalFactory, myContext, scopeAware, jvmTypeProvider, valueConverter);
            }
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AccessRestriction(org.eclipse.jdt.internal.compiler.env.AccessRestriction) IReplacementTextApplier(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal.IReplacementTextApplier) BasicSearchEngine(org.eclipse.jdt.internal.core.search.BasicSearchEngine) Builder(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext.Builder) StyledString(org.eclipse.jface.viewers.StyledString) ICompletionProposalAcceptor(org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor) IJvmTypeProvider(org.eclipse.xtext.common.types.access.IJvmTypeProvider) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IScope(org.eclipse.xtext.scoping.IScope) PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) IRestrictedAccessTypeRequestor(org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor) CharMatcher(com.google.common.base.CharMatcher) QualifiedName(org.eclipse.xtext.naming.QualifiedName) ContentAssistContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext)

Aggregations

ConfigurableCompletionProposal (org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal)35 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)21 StyledString (org.eclipse.jface.viewers.StyledString)16 IEObjectDescription (org.eclipse.xtext.resource.IEObjectDescription)8 PrefixMatcher (org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher)5 ContentAssistContext (org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext)4 EObject (org.eclipse.emf.ecore.EObject)3 QualifiedName (org.eclipse.xtext.naming.QualifiedName)3 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 EClass (org.eclipse.emf.ecore.EClass)2 EClassifier (org.eclipse.emf.ecore.EClassifier)2 EPackage (org.eclipse.emf.ecore.EPackage)2 BadLocationException (org.eclipse.jface.text.BadLocationException)2 ContextTypeRegistry (org.eclipse.jface.text.templates.ContextTypeRegistry)2 TemplateContextType (org.eclipse.jface.text.templates.TemplateContextType)2 TemplateVariableResolver (org.eclipse.jface.text.templates.TemplateVariableResolver)2 AbstractRule (org.eclipse.xtext.AbstractRule)2 EnumRule (org.eclipse.xtext.EnumRule)2 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)2 IScope (org.eclipse.xtext.scoping.IScope)2