Example usage for org.eclipse.jdt.core CompletionContext getTokenStart

List of usage examples for org.eclipse.jdt.core CompletionContext getTokenStart

Introduction

In this page you can find the example usage for org.eclipse.jdt.core CompletionContext getTokenStart.

Prototype

public int getTokenStart() 

Source Link

Document

Returns the character index of the start of the subrange in the source file buffer containing the relevant token being completed.

Usage

From source file:org.eclipse.babel.tapiji.tools.java.ui.MessageCompletionProposalComputer.java

License:Open Source License

@Override
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context,
        IProgressMonitor monitor) {//from   ww  w .  j  a  va2  s.com

    List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();

    if (!InternationalizationNature.hasNature(
            ((JavaContentAssistInvocationContext) context).getCompilationUnit().getResource().getProject())) {
        return completions;
    }

    try {
        JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
        CompletionContext coreContext = javaContext.getCoreContext();

        int tokenStart = coreContext.getTokenStart();
        int tokenEnd = coreContext.getTokenEnd();
        int tokenOffset = coreContext.getOffset();
        boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;

        if (cu == null) {
            manager = ResourceBundleManager
                    .getManager(javaContext.getCompilationUnit().getResource().getProject());

            resource = javaContext.getCompilationUnit().getResource();

            csav = new ResourceAuditVisitor(null, manager.getProject().getName());

            cu = ASTutilsUI.getAstRoot(ASTutilsUI.getCompilationUnit(resource));

            cu.accept(csav);
        }

        if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
                && (tokenEnd + 1) - tokenStart > 0) {

            // Cal10n extension
            String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos(manager.getProject().getName(), cu,
                    tokenOffset - 1);

            if (metaData != null) {
                completions.add(new KeyRefactoringProposal(tokenOffset, metaData[1],
                        manager.getProject().getName(), metaData[0], metaData[2]));
            }

            return completions;
        }

        if (tokenStart < 0) {
            // is string literal in front of cursor?
            StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu, tokenOffset - 1);
            if (strLit != null) {
                tokenStart = strLit.getStartPosition();
                tokenEnd = tokenStart + strLit.getLength() - 1;
                tokenOffset = tokenOffset - 1;
                isStringLiteral = true;
            } else {
                tokenStart = tokenOffset;
                tokenEnd = tokenOffset;
            }
        }

        if (isStringLiteral) {
            tokenStart++;
        }

        tokenEnd = Math.max(tokenEnd, tokenStart);

        String fullToken = "";

        if (tokenStart < tokenEnd) {
            fullToken = context.getDocument().get(tokenStart, tokenEnd - tokenStart);
        }

        // Check if the string literal is up to be written within the
        // context of a resource-bundle accessor method
        if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
            completions.addAll(getResourceBundleCompletionProposals(tokenStart, tokenEnd, tokenOffset,
                    isStringLiteral, fullToken, manager, csav, resource));
        } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null && isStringLiteral) {
            completions.addAll(getRBReferenceCompletionProposals(tokenStart, tokenEnd, fullToken,
                    isStringLiteral, manager, resource));
        } else {
            completions.addAll(getBasicJavaCompletionProposals(tokenStart, tokenEnd, tokenOffset, fullToken,
                    isStringLiteral, manager, csav, resource));
        }
        if (completions.size() == 1) {
            completions.add(new NoActionProposal());
        }

    } catch (Exception e) {
        Logger.logError(e);
    }
    return completions;
}

From source file:org.eclipse.jpt.jaxb.ui.internal.JaxbJavaCompletionProposalComputer.java

License:Open Source License

private List<ICompletionProposal> computeCompletionProposals_(JavaContentAssistInvocationContext context) {
    ICompilationUnit cu = context.getCompilationUnit();
    IFile file = (cu != null) ? getCorrespondingResource(cu) : null;
    IContentType contentType = (file != null) ? ContentTypeTools.contentType(file) : null;

    if (contentType == null || !contentType.isKindOf(JavaResourceCompilationUnit.CONTENT_TYPE)) {
        return Collections.emptyList();
    }/*from   w ww.ja  v a 2 s.  c  o  m*/

    JaxbProject jaxbProject = this.getJaxbProject(file.getProject());
    if (jaxbProject == null) {
        return Collections.emptyList();
    }

    Iterable<? extends JaxbContextNode> javaNodes = jaxbProject.getPrimaryJavaNodes(cu);
    if (IterableTools.isEmpty(javaNodes)) {
        return Collections.emptyList();
    }

    CompletionContext cc = context.getCoreContext();

    // the context's "token" is really a sort of "prefix" - it does NOT
    // correspond to the "start" and "end" we get below... 
    char[] prefix = cc.getToken();
    Predicate<String> filter = this.buildPrefixFilter(prefix);
    // the token "kind" tells us if we are in a String literal already - CompletionContext.TOKEN_KIND_STRING_LITERAL
    int tokenKind = cc.getTokenKind();
    // the token "start" is the offset of the token's first character
    int tokenStart = cc.getTokenStart();
    // the token "end" is the offset of the token's last character (yuk)
    int tokenEnd = cc.getTokenEnd();
    if (tokenStart == -1) { // not sure why this happens - see bug 242286
        return Collections.emptyList();
    }

    //      System.out.println("token start: " + tokenStart);
    //      System.out.println("token end: " + tokenEnd);
    //      System.out.println("token kind: " + tokenKind);
    //      String source = cu.getSource();
    //      String token = source.substring(Math.max(0, tokenStart), Math.min(source.length(), tokenEnd + 1));
    //      System.out.println("token: =>" + token + "<=");
    //      String snippet = source.substring(Math.max(0, tokenStart - 20), Math.min(source.length(), tokenEnd + 21));
    //      System.out.println("surrounding snippet: =>" + snippet + "<=");

    List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
    for (JaxbContextNode javaNode : javaNodes) {
        for (String proposal : this.buildCompletionProposals(javaNode, context.getInvocationOffset(), filter)) {
            if (tokenKind == CompletionContext.TOKEN_KIND_STRING_LITERAL) {//already quoted
                proposals.add(new CompletionProposal(proposal, tokenStart, tokenEnd - tokenStart - 1,
                        proposal.length()));
            } else {//add the quotes
                proposals.add(new CompletionProposal("\"" + proposal + "\"", tokenStart, //$NON-NLS-1$//$NON-NLS-2$
                        tokenEnd - tokenStart + 1, proposal.length() + 2));
            }
        }
    }
    return proposals;
}

From source file:org.eclipse.jpt.jpa.ui.internal.JpaJavaCompletionProposalComputer.java

License:Open Source License

private List<ICompletionProposal> computeCompletionProposals_(JavaContentAssistInvocationContext context) {
    ICompilationUnit cu = context.getCompilationUnit();
    if (cu == null) {
        return Collections.emptyList();
    }//  www . j  a  va  2 s  .  c om

    IFile file = this.getCorrespondingResource(cu);
    if (file == null) {
        return Collections.emptyList();
    }

    JpaFile jpaFile = this.getJpaFile(file);
    if (jpaFile == null) {
        return Collections.emptyList();
    }

    Collection<JpaStructureNode> rootStructureNodes = CollectionTools
            .collection(jpaFile.getRootStructureNodes());
    if (rootStructureNodes.isEmpty()) {
        return Collections.emptyList();
    }

    CompletionContext cc = context.getCoreContext();

    // the context's "token" is really a sort of "prefix" - it does NOT
    // correspond to the "start" and "end" we get below... 
    char[] prefix = cc.getToken();
    Predicate<String> filter = this.buildPrefixFilter(prefix);
    // the token "kind" tells us if we are in a String literal already - CompletionContext.TOKEN_KIND_STRING_LITERAL
    int tokenKind = cc.getTokenKind();
    // the token "start" is the offset of the token's first character
    int tokenStart = cc.getTokenStart();
    // the token "end" is the offset of the token's last character (yuk)
    int tokenEnd = cc.getTokenEnd();
    if (tokenStart == -1) { // not sure why this happens - see bug 242286
        return Collections.emptyList();
    }

    //      System.out.println("token start: " + tokenStart);
    //      System.out.println("token end: " + tokenEnd);
    //      System.out.println("token kind: " + tokenKind);
    //      String source = cu.getSource();
    //      String token = source.substring(Math.max(0, tokenStart), Math.min(source.length(), tokenEnd + 1));
    //      System.out.println("token: =>" + token + "<=");
    //      String snippet = source.substring(Math.max(0, tokenStart - 20), Math.min(source.length(), tokenEnd + 21));
    //      System.out.println("surrounding snippet: =>" + snippet + "<=");

    List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
    for (JpaStructureNode structureNode : rootStructureNodes) {
        for (String s : this.buildCompletionProposals((JavaPersistentType) structureNode,
                context.getInvocationOffset(), filter)) {
            if (tokenKind == CompletionContext.TOKEN_KIND_STRING_LITERAL) {//already quoted
                proposals.add(new CompletionProposal(s, tokenStart + 1, tokenEnd - tokenStart - 1, s.length()));
            } else {//add the quotes
                proposals.add(new CompletionProposal("\"" + s + "\"", tokenStart, tokenEnd - tokenStart + 1, //$NON-NLS-1$//$NON-NLS-2$
                        s.length() + 2));
            }
        }
    }
    return proposals;
}

From source file:org.eclipse.jpt.jpa.ui.internal.jpql.JpaJpqlJavaCompletionProposalComputer.java

License:Open Source License

private List<ICompletionProposal> computeCompletionProposals(JavaContentAssistInvocationContext context,
        IProgressMonitor monitor) throws Exception {

    CompletionContext completionContext = context.getCoreContext();
    if (completionContext == null)
        return Collections.emptyList();

    // The token "start" is the offset of the token's first character within the document.
    // A token start of -1 can means:
    // - It is inside the string representation of a unicode character, \\u0|0E9 where | is the
    //   cursor, then -1 is returned;
    // - The string is not valid (it has some invalid characters)
    int tokenStart[] = { completionContext.getTokenStart() };
    int tokenEnd[] = { completionContext.getTokenEnd() };
    if (tokenStart[0] == -1)
        return Collections.emptyList();

    int[] position = { completionContext.getOffset() - tokenStart[0] - 1 };
    if (position[0] < 0)
        return Collections.emptyList();

    ICompilationUnit compilationUnit = context.getCompilationUnit();
    if (compilationUnit == null)
        return Collections.emptyList();
    CompilationUnit astRoot = ASTTools.buildASTRoot(compilationUnit);

    IFile file = getCorrespondingResource(compilationUnit);
    if (file == null)
        return Collections.emptyList();

    JpaFile jpaFile = (JpaFile) file.getAdapter(JpaFile.class);
    if (jpaFile == null)
        return Collections.emptyList();

    monitor.worked(80);/* w w  w.jav  a  2  s  .c o m*/
    checkCanceled(monitor);

    // Retrieve the JPA's model object
    NamedQuery namedQuery = namedQuery(jpaFile, tokenStart[0]);
    if (namedQuery == null)
        return Collections.emptyList();

    // Retrieve the actual value of the element "query" since the content assist can be
    // invoked before the model received the new content
    String jpqlQuery = retrieveQuery(astRoot, tokenStart, tokenEnd, position);

    // Now create the proposals
    ResourceManager resourceManager = this.getResourceManager(context.getViewer().getTextWidget());
    return buildProposals(namedQuery, jpqlQuery, tokenStart[0], tokenEnd[0], position[0], resourceManager);
}

From source file:org.eclipse.pde.api.tools.ui.internal.completion.APIToolsJavadocCompletionProposalComputer.java

License:Open Source License

/**
 * Computes all of the Javadoc completion proposals
 * /*  w  w w .j  a va2s.  co  m*/
 * @param jcontext
 * @param corecontext
 * @return the complete list of Javadoc completion proposals or an empty
 *         list, never <code>null</code>
 * @since 1.0.500
 */
List<ICompletionProposal> computeJavadocProposals(JavaContentAssistInvocationContext jcontext,
        CompletionContext corecontext) {
    ICompilationUnit cunit = jcontext.getCompilationUnit();
    if (cunit != null) {
        try {
            int offset = jcontext.getInvocationOffset();
            IJavaElement element = cunit.getElementAt(offset);
            if (!isVisible(element)) {
                return Collections.EMPTY_LIST;
            }
            ImageDescriptor imagedesc = jcontext.getLabelProvider()
                    .createImageDescriptor(org.eclipse.jdt.core.CompletionProposal
                            .create(org.eclipse.jdt.core.CompletionProposal.JAVADOC_BLOCK_TAG, offset));
            fImageHandle = (imagedesc == null ? null : imagedesc.createImage());
            int type = getType(element);
            int member = IApiJavadocTag.MEMBER_NONE;
            switch (element.getElementType()) {
            case IJavaElement.METHOD: {
                IMethod method = (IMethod) element;
                member = IApiJavadocTag.MEMBER_METHOD;
                if (method.isConstructor()) {
                    member = IApiJavadocTag.MEMBER_CONSTRUCTOR;
                }
                break;
            }
            case IJavaElement.FIELD: {
                member = IApiJavadocTag.MEMBER_FIELD;
                break;
            }
            default:
                break;
            }
            IApiJavadocTag[] tags = ApiPlugin.getJavadocTagManager().getTagsForType(type, member);
            int tagcount = tags.length;
            if (tagcount > 0) {
                ArrayList<ICompletionProposal> list = null;
                collectExistingTags(element, jcontext);
                String completiontext = null;
                int tokenstart = corecontext.getTokenStart();
                int length = offset - tokenstart;
                for (int i = 0; i < tagcount; i++) {
                    if (!acceptTag(tags[i], element)) {
                        continue;
                    }
                    completiontext = tags[i].getCompleteTag(type, member);
                    if (appliesToContext(jcontext.getDocument(), completiontext, tokenstart,
                            (length > 0 ? length : 1))) {
                        if (list == null) {
                            list = new ArrayList<ICompletionProposal>(tagcount - i);
                        }
                        list.add(new APIToolsJavadocCompletionProposal(corecontext, completiontext,
                                tags[i].getTagName(), fImageHandle));
                    }
                }
                if (list != null) {
                    return list;
                }
            }
        } catch (JavaModelException e) {
            fErrorMessage = e.getMessage();
        }
    }
    return Collections.EMPTY_LIST;
}

From source file:org.eclipselabs.stlipse.javaeditor.JavaCompletionProposalComputer.java

License:Open Source License

public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context,
        IProgressMonitor monitor) {/*w  w w  .  j  a v  a 2  s .com*/
    List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
    if (context instanceof JavaContentAssistInvocationContext) {
        JavaContentAssistInvocationContext javaContext = (JavaContentAssistInvocationContext) context;
        CompletionContext coreContext = javaContext.getCoreContext();
        ICompilationUnit unit = javaContext.getCompilationUnit();
        try {
            if (unit != null && unit.isStructureKnown()) {
                int offset = javaContext.getInvocationOffset();
                IJavaElement element = unit.getElementAt(offset);
                if (element != null && element instanceof IAnnotatable) {
                    ValueInfo valueInfo = scanAnnotation(offset, (IAnnotatable) element);
                    if (valueInfo != null) {
                        int replacementLength = valueInfo.getValueLength();
                        IJavaProject project = javaContext.getProject();
                        String beanFqn = unit.getType(element.getParent().getElementName())
                                .getFullyQualifiedName();
                        if (valueInfo.isField()) {
                            if (valueInfo.isPropertyOmmitted()) {
                                StringBuilder matchStr = resolveBeanPropertyName(element);
                                if (matchStr.length() > 0) {
                                    char[] token = coreContext.getToken();
                                    matchStr.append('.').append(token);
                                    Map<String, String> fields = BeanPropertyCache.searchFields(project,
                                            beanFqn, matchStr.toString(), false, -1, false);
                                    proposals.addAll(BeanPropertyCache.buildFieldNameProposal(fields,
                                            String.valueOf(token), coreContext.getTokenStart() + 1,
                                            replacementLength));
                                }
                            } else {
                                String input = String.valueOf(coreContext.getToken());
                                Map<String, String> fields = BeanPropertyCache.searchFields(project, beanFqn,
                                        input, false, -1, false);
                                proposals.addAll(BeanPropertyCache.buildFieldNameProposal(fields, input,
                                        coreContext.getTokenStart() + 1, replacementLength));
                            }
                        } else if (valueInfo.isEventHandler()) {
                            String input = String.valueOf(coreContext.getToken());
                            boolean isNot = false;
                            if (input.length() > 0 && input.startsWith("!")) {
                                isNot = true;
                                input = input.length() > 1 ? input.substring(1) : "";
                            }
                            List<String> events = BeanPropertyCache.searchEventHandler(project, beanFqn, input,
                                    false, false);
                            int relevance = events.size();
                            for (String event : events) {
                                String replaceStr = isNot ? "!" + event : event;
                                ICompletionProposal proposal = new JavaCompletionProposal(replaceStr,
                                        coreContext.getTokenStart() + 1, replacementLength, replaceStr.length(),
                                        Activator.getIcon(), event, null, null, relevance--);
                                proposals.add(proposal);
                            }
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            Activator.log(Status.ERROR, "Something went wrong.", e);
        }
    }
    return proposals;
}

From source file:org.nuxeo.ide.connect.completion.StudioProposalComputer.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override//from   w w w  . j a  v  a2 s.com
public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {

    if (context instanceof JavaContentAssistInvocationContext) {
        JavaContentAssistInvocationContext jctx = (JavaContentAssistInvocationContext) context;
        IJavaProject jproject = jctx.getProject();
        if (jproject == null) {
            return Collections.emptyList();
        }
        StudioProjectBinding binding = ConnectPlugin.getStudioProvider().getBinding(jproject.getProject());
        if (binding == null) {
            return Collections.emptyList();
        }
        // look if we are in a string literal and initialize locations
        CompletionContext cc = jctx.getCoreContext();
        int offset = context.getInvocationOffset();
        int replacementLength = -1;
        String prefix = null;
        if (cc.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL) {
            offset = cc.getTokenStart();
            int end = cc.getTokenEnd();
            replacementLength = end - offset + 1;
            prefix = new String(cc.getToken());
        } else {
            Point p = jctx.getViewer().getSelectedRange();
            replacementLength = p.y;
        }

        // assignment case
        IType type = jctx.getExpectedType();
        if (type != null && "java.lang.String".equals(type.getFullyQualifiedName())) {
            StudioAssignmentProposalCollector collector = new StudioAssignmentProposalCollector(jctx, binding);
            collector.initialize(offset, replacementLength, prefix);
            return collector.getProposals();
        }
        // method arg case
        ICompilationUnit unit = jctx.getCompilationUnit();
        StudioArgumentProposalCollector collector = new StudioArgumentProposalCollector(jctx, binding);
        collector.initialize(offset, replacementLength, prefix);
        try {
            unit.codeComplete(offset, collector, new NullProgressMonitor());
            return collector.getProposals();
        } catch (Exception e) {
            UI.showError("Error while compiling studio proposal", e);
        }
    }
    return Collections.emptyList();
}