Search in sources :

Example 1 with PrefixMatcher

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

the class TerminalsProposalProvider method complete_ID.

public void complete_ID(EObject model, RuleCall ruleCall, final ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
    if (doCreateIdProposals()) {
        PrefixMatcher newMatcher = new PrefixMatcher() {

            @Override
            public boolean isCandidateMatchingPrefix(String name, String prefix) {
                String strippedName = name;
                if (name.startsWith("^") && !prefix.startsWith("^")) {
                    strippedName = name.substring(1);
                }
                return context.getMatcher().isCandidateMatchingPrefix(strippedName, prefix);
            }
        };
        ContentAssistContext myContext = context.copy().setMatcher(newMatcher).toContext();
        String feature = getAssignedFeature(ruleCall);
        String proposalText = feature != null ? feature : Strings.toFirstUpper(ruleCall.getRule().getName().toLowerCase());
        String displayText = proposalText;
        if (feature != null)
            displayText = proposalText + " - " + ruleCall.getRule().getName();
        proposalText = getValueConverter().toString(proposalText, ruleCall.getRule().getName());
        ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, myContext);
        if (proposal instanceof ConfigurableCompletionProposal) {
            ConfigurableCompletionProposal configurable = (ConfigurableCompletionProposal) proposal;
            configurable.setSelectionStart(configurable.getReplacementOffset());
            configurable.setSelectionLength(proposalText.length());
            configurable.setAutoInsertable(false);
            configurable.setSimpleLinkedMode(myContext.getViewer(), '\t', ' ');
        }
        acceptor.accept(proposal);
    }
}
Also used : PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ContentAssistContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal)

Example 2 with PrefixMatcher

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

the class ImplementMemberFromSuperAssist method createOverrideMethodProposal.

protected ICompletionProposal createOverrideMethodProposal(XtendTypeDeclaration model, IResolvedExecutable overrideable, final ContentAssistContext context, IProposalConflictHelper conflictHelper) {
    IXtextDocument document = context.getDocument();
    XtextResource resource = (XtextResource) model.eResource();
    int offset = context.getReplaceRegion().getOffset();
    int currentIndentation = appendableFactory.getIndentationLevelAtOffset(offset, document, resource);
    final int indentationLevel = currentIndentation == 0 ? 1 : currentIndentation;
    ReplacingAppendable appendable = appendableFactory.create(document, resource, offset, context.getReplaceRegion().getLength(), new OptionalParameters() {

        {
            ensureEmptyLinesAround = true;
            baseIndentationLevel = indentationLevel;
        }
    });
    final String simpleName;
    JvmExecutable declaration = overrideable.getDeclaration();
    if (overrideable instanceof IResolvedOperation) {
        implementor.appendOverrideFunction(model, (IResolvedOperation) overrideable, appendable);
        simpleName = overrideable.getDeclaration().getSimpleName();
    } else if (model instanceof XtendClass) {
        implementor.appendConstructorFromSuper((XtendClass) model, (IResolvedConstructor) overrideable, appendable);
        simpleName = "new";
    } else {
        return null;
    }
    String code = appendable.getCode();
    if (!isValidProposal(code.trim(), context, conflictHelper) && !isValidProposal(simpleName, context, conflictHelper))
        return null;
    ImageDescriptor imageDescriptor = images.forOperation(declaration.getVisibility(), adornments.getOverrideAdornment(declaration));
    ImportOrganizingProposal completionProposal = createCompletionProposal(appendable, context.getReplaceRegion(), getLabel(overrideable), imageHelper.getImage(imageDescriptor));
    Matcher matcher = bodyExpressionPattern.matcher(code);
    if (matcher.find()) {
        int bodyExpressionLength = matcher.end(1) - matcher.start(1);
        int bodyExpressionStart = matcher.start(1) + appendable.getTotalOffset() - completionProposal.getReplacementOffset();
        if (bodyExpressionLength == 0) {
            completionProposal.setCursorPosition(bodyExpressionStart);
        } else {
            completionProposal.setSelectionStart(completionProposal.getReplacementOffset() + bodyExpressionStart);
            completionProposal.setSelectionLength(bodyExpressionLength);
            completionProposal.setAutoInsertable(false);
            completionProposal.setCursorPosition(bodyExpressionStart + bodyExpressionLength);
            completionProposal.setSimpleLinkedMode(context.getViewer(), '\t');
        }
    }
    completionProposal.setPriority(getPriority(model, declaration, context));
    completionProposal.setMatcher(new PrefixMatcher() {

        @Override
        public boolean isCandidateMatchingPrefix(String name, String prefix) {
            PrefixMatcher delegate = context.getMatcher();
            boolean result = delegate.isCandidateMatchingPrefix(simpleName, prefix);
            return result;
        }
    });
    return completionProposal;
}
Also used : PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) Matcher(java.util.regex.Matcher) XtextResource(org.eclipse.xtext.resource.XtextResource) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) StyledString(org.eclipse.jface.viewers.StyledString) IResolvedOperation(org.eclipse.xtext.xbase.typesystem.override.IResolvedOperation) IResolvedConstructor(org.eclipse.xtext.xbase.typesystem.override.IResolvedConstructor) OptionalParameters(org.eclipse.xtext.xbase.ui.document.DocumentSourceAppender.Factory.OptionalParameters) JvmExecutable(org.eclipse.xtext.common.types.JvmExecutable) XtendClass(org.eclipse.xtend.core.xtend.XtendClass) ImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) ImportOrganizingProposal(org.eclipse.xtext.xbase.ui.contentassist.ImportOrganizingProposal) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 3 with PrefixMatcher

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

the class CodetemplatesProposalProvider method completeVariable_Name.

@Override
public void completeVariable_Name(EObject model, Assignment assignment, final ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
    if ((mode & NORMAL) != 0) {
        {
            String proposalText = "variable";
            StyledString displayText = new StyledString(proposalText).append(" - Create a new template variable", StyledString.QUALIFIER_STYLER);
            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);
        }
        TemplateData data = new TemplateData(model);
        if (data.doCreateProposals()) {
            ContextTypeIdHelper helper = languageRegistry.getContextTypeIdHelper(data.language);
            if (helper != null) {
                String contextTypeId = helper.getId(data.rule);
                ContextTypeRegistry contextTypeRegistry = languageRegistry.getContextTypeRegistry(data.language);
                TemplateContextType contextType = contextTypeRegistry.getContextType(contextTypeId);
                if (contextType != null) {
                    Iterator<TemplateVariableResolver> resolvers = Iterators.filter(contextType.resolvers(), TemplateVariableResolver.class);
                    while (resolvers.hasNext()) {
                        final TemplateVariableResolver resolver = resolvers.next();
                        IInspectableTemplateVariableResolver inspectableResolver = templateVariableResolverRegistry.toInspectableResolver(resolver);
                        if (inspectableResolver != null) {
                            if (!inspectableResolver.hasMandatoryParameters()) {
                                String type = resolver.getType();
                                StyledString displayString = new StyledString(type, StyledString.DECORATIONS_STYLER).append(" - " + resolver.getDescription(), StyledString.QUALIFIER_STYLER);
                                acceptor.accept(createCompletionProposal(type, displayString, null, context));
                            }
                            String proposalText = "variable:" + resolver.getType();
                            StyledString displayText = new StyledString("variable").append(":" + resolver.getType(), StyledString.DECORATIONS_STYLER).append(" - " + resolver.getDescription(), StyledString.QUALIFIER_STYLER);
                            if (inspectableResolver.hasMandatoryParameters())
                                proposalText = proposalText + "()";
                            Builder builder = context.copy();
                            PrefixMatcher newMatcher = new PrefixMatcher() {

                                @Override
                                public boolean isCandidateMatchingPrefix(String name, String prefix) {
                                    return context.getMatcher().isCandidateMatchingPrefix(name, prefix) || context.getMatcher().isCandidateMatchingPrefix("variable:" + resolver.getType(), prefix) || context.getMatcher().isCandidateMatchingPrefix(resolver.getType(), prefix);
                                }
                            };
                            builder.setMatcher(newMatcher);
                            ContentAssistContext myContext = builder.toContext();
                            ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, myContext);
                            if (proposal instanceof ConfigurableCompletionProposal) {
                                ConfigurableCompletionProposal configurable = (ConfigurableCompletionProposal) proposal;
                                configurable.setSelectionStart(configurable.getReplacementOffset());
                                configurable.setSelectionLength("variable".length());
                                configurable.setAutoInsertable(false);
                                if (inspectableResolver.hasMandatoryParameters()) {
                                    configurable.setCursorPosition(proposalText.length() - 1);
                                }
                                configurable.setSimpleLinkedMode(myContext.getViewer(), '\t');
                            }
                            acceptor.accept(proposal);
                        } else {
                            String type = resolver.getType();
                            StyledString displayString = new StyledString(type, StyledString.DECORATIONS_STYLER).append(" - " + resolver.getDescription(), StyledString.QUALIFIER_STYLER);
                            acceptor.accept(createCompletionProposal(type, displayString, null, context));
                        }
                    }
                }
            }
            if (data.template.getBody() != null) {
                for (Variable variable : Iterables.filter(data.template.getBody().getParts(), Variable.class)) {
                    if (variable != model && variable.getName() != null) {
                        String proposalText = variable.getName();
                        StyledString displayText = new StyledString(proposalText).append(" - existing variable", StyledString.QUALIFIER_STYLER);
                        if (variable.getType() != null)
                            displayText = displayText.append(" of type " + variable.getType(), StyledString.QUALIFIER_STYLER);
                        ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, context);
                        acceptor.accept(proposal);
                    }
                }
            }
        }
    }
}
Also used : PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) Variable(org.eclipse.xtext.ui.codetemplates.templates.Variable) Builder(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext.Builder) ContextTypeRegistry(org.eclipse.jface.text.templates.ContextTypeRegistry) StyledString(org.eclipse.jface.viewers.StyledString) StyledString(org.eclipse.jface.viewers.StyledString) ContextTypeIdHelper(org.eclipse.xtext.ui.editor.templates.ContextTypeIdHelper) IInspectableTemplateVariableResolver(org.eclipse.xtext.ui.codetemplates.ui.resolvers.IInspectableTemplateVariableResolver) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) ContentAssistContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext) TemplateContextType(org.eclipse.jface.text.templates.TemplateContextType) IInspectableTemplateVariableResolver(org.eclipse.xtext.ui.codetemplates.ui.resolvers.IInspectableTemplateVariableResolver) TemplateVariableResolver(org.eclipse.jface.text.templates.TemplateVariableResolver)

Example 4 with PrefixMatcher

use of org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher 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 5 with PrefixMatcher

use of org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher 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)

Aggregations

PrefixMatcher (org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher)6 ConfigurableCompletionProposal (org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal)5 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)4 StyledString (org.eclipse.jface.viewers.StyledString)4 ContentAssistContext (org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)2 IEObjectDescription (org.eclipse.xtext.resource.IEObjectDescription)2 XtextResource (org.eclipse.xtext.resource.XtextResource)2 Builder (org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext.Builder)2 CharMatcher (com.google.common.base.CharMatcher)1 Matcher (java.util.regex.Matcher)1 URI (org.eclipse.emf.common.util.URI)1 EClass (org.eclipse.emf.ecore.EClass)1 EObject (org.eclipse.emf.ecore.EObject)1 EPackage (org.eclipse.emf.ecore.EPackage)1 Resource (org.eclipse.emf.ecore.resource.Resource)1 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)1 AccessRestriction (org.eclipse.jdt.internal.compiler.env.AccessRestriction)1 BasicSearchEngine (org.eclipse.jdt.internal.core.search.BasicSearchEngine)1