Search in sources :

Example 26 with ICompletionProposalHandle

use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.

the class PydevConsoleInterpreter method getCompletions.

@Override
@SuppressWarnings("unchecked")
public ICompletionProposalHandle[] getCompletions(IScriptConsoleViewer viewer, String commandLine, int position, int offset, int whatToShow) throws Exception {
    final String text = commandLine.substring(0, position);
    ActivationTokenAndQualifier tokenAndQual = PySelection.getActivationTokenAndQualifier(new Document(text), text.length(), true, false);
    String textForCompletionInConsole = PySelection.getTextForCompletionInConsole(new Document(text), text.length());
    if (PySelection.isCompletionForLiteralNumber(tokenAndQual.activationToken)) {
        // suppress completions that would be invalid
        return new ICompletionProposalHandle[0];
    }
    // Code-completion for imports
    ImportInfo importsTipper = ImportsSelection.getImportsTipperStr(text, false);
    Set<IPythonNature> natureAndRelatedNatures = getNatureAndRelatedNatures();
    if (importsTipper.importsTipperStr.length() != 0) {
        importsTipper.importsTipperStr = importsTipper.importsTipperStr.trim();
        Set<IToken> tokens = new TreeSet<IToken>();
        final boolean onlyGetDirectModules = true;
        // Check all the natures.
        for (final IPythonNature nature : natureAndRelatedNatures) {
            ICodeCompletionASTManager astManager = nature.getAstManager();
            TokensList importTokens = astManager.getCompletionsForImport(importsTipper, new ICompletionRequest() {

                @Override
                public IPythonNature getNature() {
                    return nature;
                }

                @Override
                public File getEditorFile() {
                    return null;
                }

                @Override
                public IModule getModule() throws MisconfigurationException {
                    return null;
                }
            }, onlyGetDirectModules);
            // only get all modules for the 1st one we analyze (no need to get on the others)
            for (IterTokenEntry entry : importTokens) {
                IToken iToken = entry.getToken();
                tokens.add(iToken);
            }
        }
        int qlen = tokenAndQual.qualifier.length();
        List<ICompletionProposalHandle> ret = new ArrayList<ICompletionProposalHandle>(tokens.size());
        Iterator<IToken> it = tokens.iterator();
        for (int i = 0; i < tokens.size(); i++) {
            IToken t = it.next();
            int replacementOffset = offset - qlen;
            String representation = t.getRepresentation();
            if (representation.startsWith(tokenAndQual.qualifier)) {
                ret.add(CompletionProposalFactory.get().createPyLinkedModeCompletionProposal(representation, replacementOffset, qlen, representation.length(), t, null, null, IPyCompletionProposal.PRIORITY_DEFAULT, IPyCompletionProposal.ON_APPLY_DEFAULT, "", null));
            }
        }
        return ret.toArray(new ICompletionProposalHandle[ret.size()]);
    }
    // END Code-completion for imports
    String actTok = tokenAndQual.activationToken;
    if (tokenAndQual.qualifier != null && tokenAndQual.qualifier.length() > 0) {
        if (actTok.length() > 0 && actTok.charAt(actTok.length() - 1) != '.') {
            actTok += '.';
        }
        actTok += tokenAndQual.qualifier;
    }
    boolean showOnlyTemplates = whatToShow == AbstractCompletionProcessorWithCycling.SHOW_ONLY_TEMPLATES;
    boolean showForTabCompletion = whatToShow == AbstractCompletionProcessorWithCycling.SHOW_FOR_TAB_COMPLETIONS;
    // simple completions (clients)
    ArrayList<ICompletionProposalHandle> results = new ArrayList<ICompletionProposalHandle>();
    if (!showForTabCompletion) {
        for (ISimpleAssistParticipant2 participant : simpleParticipants) {
            results.addAll(participant.computeConsoleProposals(tokenAndQual.activationToken, tokenAndQual.qualifier, offset));
        }
    }
    ProposalsComparator proposalsComparator = new ProposalsComparator(tokenAndQual.qualifier, null);
    ArrayList<ICompletionProposalHandle> results2 = new ArrayList<ICompletionProposalHandle>();
    if (!showOnlyTemplates) {
        // shell completions
        if (consoleCommunication != null) {
            ICompletionProposalHandle[] consoleCompletions = consoleCommunication.getCompletions(text, textForCompletionInConsole, offset, showForTabCompletion);
            // If we're only showing ipython completions, then short-circuit the rest
            if (showForTabCompletion) {
                return consoleCompletions;
            }
            results2.addAll(Arrays.asList(consoleCompletions));
        }
    }
    if (tokenAndQual.activationToken.length() == 0) {
        // templates (only if we have no activation token)
        IPyTemplateCompletionProcessor pyTemplateCompletionProcessor = new PyTemplateCompletionProcessor();
        pyTemplateCompletionProcessor.addTemplateProposals((ITextViewer) viewer, offset, results2);
    }
    Collections.sort(results2, proposalsComparator);
    ArrayList<ICompletionProposalHandle> results3 = new ArrayList<ICompletionProposalHandle>();
    if (!showOnlyTemplates) {
        // other participants
        List<Object> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_COMPLETION);
        for (Object participant : participants) {
            if (participant instanceof IPyDevCompletionParticipant2) {
                IPyDevCompletionParticipant2 participant2 = (IPyDevCompletionParticipant2) participant;
                results3.addAll(participant2.computeConsoleCompletions(tokenAndQual, natureAndRelatedNatures, viewer, offset));
            }
        }
        Collections.sort(results3, proposalsComparator);
    }
    results.addAll(results2);
    results.addAll(results3);
    return results.toArray(new ICompletionProposalHandle[results.size()]);
}
Also used : IModule(org.python.pydev.core.IModule) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ISimpleAssistParticipant2(org.python.pydev.ast.simpleassist.ISimpleAssistParticipant2) IPythonNature(org.python.pydev.core.IPythonNature) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IToken(org.python.pydev.core.IToken) TreeSet(java.util.TreeSet) IPyDevCompletionParticipant2(org.python.pydev.ast.codecompletion.IPyDevCompletionParticipant2) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) ActivationTokenAndQualifier(org.python.pydev.core.docutils.PySelection.ActivationTokenAndQualifier) PyTemplateCompletionProcessor(org.python.pydev.editor.codecompletion.PyTemplateCompletionProcessor) IPyTemplateCompletionProcessor(org.python.pydev.editor.codecompletion.IPyTemplateCompletionProcessor) TokensList(org.python.pydev.core.TokensList) ICompletionRequest(org.python.pydev.core.ICompletionRequest) IPyTemplateCompletionProcessor(org.python.pydev.editor.codecompletion.IPyTemplateCompletionProcessor) IterTokenEntry(org.python.pydev.core.IterTokenEntry) ProposalsComparator(org.python.pydev.ast.codecompletion.ProposalsComparator) ImportInfo(org.python.pydev.core.ICodeCompletionASTManager.ImportInfo) ICodeCompletionASTManager(org.python.pydev.core.ICodeCompletionASTManager) File(java.io.File)

Example 27 with ICompletionProposalHandle

use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.

the class PydevConsoleQuickAssistProcessor method computeQuickAssistProposals.

/**
 * Computes quick assists for the console.
 */
@Override
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) {
    ISourceViewer sourceViewer = invocationContext.getSourceViewer();
    List<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
    if (sourceViewer instanceof ScriptConsoleViewer) {
        ScriptConsoleViewer viewer = (ScriptConsoleViewer) sourceViewer;
        // currently, only the assign quick assist is used
        AssistAssign assistAssign = new AssistAssign();
        ISelection selection = sourceViewer.getSelectionProvider().getSelection();
        if (selection instanceof ITextSelection) {
            PySelection ps = PySelectionFromEditor.createPySelectionFromEditor(sourceViewer, (ITextSelection) selection);
            int offset = viewer.getCaretOffset();
            String commandLine = viewer.getCommandLine();
            // let's calculate the 1st line that is not a whitespace.
            if (assistAssign.isValid(ps.getSelLength(), commandLine, offset)) {
                int commandLineOffset = viewer.getCommandLineOffset();
                try {
                    IDocument doc = sourceViewer.getDocument();
                    while (true) {
                        if (commandLineOffset == doc.getLength() - 1) {
                            break;
                        }
                        char c = doc.getChar(commandLineOffset);
                        if (Character.isWhitespace(c)) {
                            commandLineOffset++;
                        } else {
                            break;
                        }
                    }
                    props.addAll(assistAssign.getProps(ps, SharedUiPlugin.getImageCache(), sourceViewer, offset, commandLine, commandLineOffset));
                } catch (BadLocationException e) {
                    Log.log(e);
                }
            }
        }
    }
    return ConvertCompletionProposals.convertHandlesToProposals(props.toArray(new ICompletionProposalHandle[props.size()]));
}
Also used : ArrayList(java.util.ArrayList) AssistAssign(org.python.pydev.editor.correctionassist.heuristics.AssistAssign) ITextSelection(org.eclipse.jface.text.ITextSelection) ScriptConsoleViewer(org.python.pydev.shared_interactive_console.console.ui.internal.ScriptConsoleViewer) ISelection(org.eclipse.jface.viewers.ISelection) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) PySelection(org.python.pydev.core.docutils.PySelection) ISourceViewer(org.eclipse.jface.text.source.ISourceViewer) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 28 with ICompletionProposalHandle

use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.

the class PydevDebugConsoleCommunication method getCompletions.

@Override
public ICompletionProposalHandle[] getCompletions(String text, String actTok, int offset, boolean showForTabCompletion) throws Exception {
    ICompletionProposalHandle[] receivedCompletions = {};
    if (waitingForInput) {
        return new ICompletionProposalHandle[0];
    }
    PyStackFrame frame = consoleFrameProvider.getLastSelectedFrame();
    if (frame == null) {
        return new ICompletionProposalHandle[0];
    }
    final EvaluateDebugConsoleExpression evaluateDebugConsoleExpression = new EvaluateDebugConsoleExpression(frame);
    String result = evaluateDebugConsoleExpression.getCompletions(actTok, offset);
    if (result.length() > 0) {
        List<Object[]> fromServer = XMLUtils.convertXMLcompletionsFromConsole(result);
        List<ICompletionProposalHandle> ret = new ArrayList<ICompletionProposalHandle>();
        PydevConsoleCommunication.convertConsoleCompletionsToICompletions(text, actTok, offset, fromServer, ret, false);
        receivedCompletions = ret.toArray(new ICompletionProposalHandle[ret.size()]);
    }
    return receivedCompletions;
}
Also used : PyStackFrame(org.python.pydev.debug.model.PyStackFrame) ArrayList(java.util.ArrayList) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)

Example 29 with ICompletionProposalHandle

use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.

the class PydevConsoleCommunication method convertToICompletions.

private static void convertToICompletions(final String text, String actTok, int offset, Object fromServer, List<ICompletionProposalHandle> ret, boolean showForTabCompletion, IFilterCompletion filter) {
    if (fromServer instanceof Object[]) {
        Object[] objects = (Object[]) fromServer;
        fromServer = Arrays.asList(objects);
    }
    if (fromServer instanceof List) {
        int length = actTok.lastIndexOf('.');
        if (length == -1) {
            length = actTok.length();
        } else {
            length = actTok.length() - length - 1;
        }
        final String trimmedText = text.trim();
        List comps = (List) fromServer;
        for (Object o : comps) {
            if (o instanceof Object[]) {
                // name, doc, args, type
                Object[] comp = (Object[]) o;
                String name = (String) comp[0];
                String docStr = (String) comp[1];
                int type = extractInt(comp[3]);
                String args = AbstractPyCodeCompletion.getArgs((String) comp[2], type, ICompletionState.LookingFor.LOOKING_FOR_INSTANCED_VARIABLE);
                String nameAndArgs = name + args;
                int priority = IPyCompletionProposal.PRIORITY_DEFAULT;
                if (type == IToken.TYPE_LOCAL) {
                    priority = IPyCompletionProposal.PRIORITY_LOCALS;
                } else if (type == IToken.TYPE_PARAM) {
                    priority = IPyCompletionProposal.PRIORITY_LOCALS_1;
                } else if (type == IToken.TYPE_IPYTHON_MAGIC) {
                    priority = IPyCompletionProposal.PRIORTTY_IPYTHON_MAGIC;
                }
                // ret.add(new PyCompletionProposal(name,
                // offset-length, length, name.length(),
                // PyCodeCompletionImages.getImageForType(type), name, null, docStr, priority));
                int cursorPos = name.length();
                if (args.length() > 1) {
                    cursorPos += 1;
                }
                int replacementOffset = offset - length;
                PyCalltipsContextInformation pyContextInformation = null;
                if (args.length() > 2) {
                    pyContextInformation = new PyCalltipsContextInformation(args, replacementOffset + name.length() + // just after the parenthesis
                    1);
                } else {
                    // i.e.: %completions, cd ...
                    if (name.length() > 0) {
                        // as ipthon completes a<tab> to %alias etc.
                        if (name.charAt(0) == '%' && text.length() > 0 && text.charAt(0) == '%') {
                            replacementOffset -= 1;
                        // handle cd -- we handle this by returning the full path from ipython
                        // TODO: perhaps we could do this for all completions
                        } else if (trimmedText.equals("cd") || trimmedText.startsWith("cd ") || trimmedText.equals("%cd") || trimmedText.startsWith("%cd ")) {
                            if (showForTabCompletion) {
                                replacementOffset = 0;
                                length = text.length();
                            } else {
                                if (name.charAt(0) == '/') {
                                    // Should be something as cd c:/temp/foo (and name is /temp/foo)
                                    char[] chars = text.toCharArray();
                                    for (int i = 0; i < chars.length; i++) {
                                        char c = chars[i];
                                        if (c == name.charAt(0)) {
                                            String sub = text.substring(i, text.length());
                                            if (name.startsWith(sub)) {
                                                replacementOffset -= (sub.length() - FullRepIterable.getLastPart(actTok).length());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                ICompletionProposalHandle completion = CompletionProposalFactory.get().createPyLinkedModeCompletionProposal(nameAndArgs, replacementOffset, length, cursorPos, PyCodeCompletionImages.getImageForType(type), nameAndArgs, pyContextInformation, docStr, priority, IPyCompletionProposal.ON_APPLY_DEFAULT, args, false, null);
                if (filter == null || filter.acceptCompletion(type, completion)) {
                    ret.add(completion);
                }
            }
        }
    }
}
Also used : PyCalltipsContextInformation(org.python.pydev.editor.codefolding.PyCalltipsContextInformation) List(java.util.List) ArrayList(java.util.ArrayList) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)

Example 30 with ICompletionProposalHandle

use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.

the class PydevConsoleCompletionProcessor method computeCompletionProposals.

/**
 * Get the completions (and cycle the completion mode if needed).
 */
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer v, int offset) {
    // cycle if we're in a new activation for requests (a second ctrl+space or
    // a new request)
    boolean cycleRequest;
    if (lastActivationCount == -1) {
        // new request: don't cycle
        lastActivationCount = this.contentAssistant.lastActivationCount;
        cycleRequest = false;
        updateStatus();
    } else {
        // we already had a request (so, we may cycle or not depending on the activation count)
        cycleRequest = this.contentAssistant.lastActivationCount != lastActivationCount;
    }
    if (cycleRequest) {
        lastActivationCount = this.contentAssistant.lastActivationCount;
        doCycle();
        updateStatus();
    }
    IScriptConsoleViewer viewer = (IScriptConsoleViewer) v;
    try {
        if (!PyCodeCompletionPreferences.useCodeCompletion()) {
            return new ICompletionProposal[0];
        }
        String commandLine = viewer.getCommandLine();
        int cursorPosition = offset - viewer.getCommandLineOffset();
        ICompletionProposalHandle[] completions = interpreterShell.getCompletions(viewer, commandLine, cursorPosition, offset, this.whatToShow);
        return ConvertCompletionProposals.convertHandlesToProposals(completions);
    } catch (Exception e) {
        Log.log(e);
        CompletionError completionError = new CompletionError(e);
        this.errorMessage = completionError.getErrorMessage();
        // Make the error visible to the user!
        return new ICompletionProposal[] { completionError };
    }
}
Also used : IScriptConsoleViewer(org.python.pydev.core.interactive_console.IScriptConsoleViewer) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) CompletionError(org.python.pydev.editor.codecompletion.CompletionError)

Aggregations

ICompletionProposalHandle (org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)165 Document (org.eclipse.jface.text.Document)72 PySelection (org.python.pydev.core.docutils.PySelection)60 ArrayList (java.util.ArrayList)34 IDocument (org.eclipse.jface.text.IDocument)15 TokensOrProposalsList (org.python.pydev.core.TokensOrProposalsList)11 FastStringBuffer (org.python.pydev.shared_core.string.FastStringBuffer)11 PyEdit (org.python.pydev.editor.PyEdit)9 BadLocationException (org.eclipse.jface.text.BadLocationException)8 IPythonNature (org.python.pydev.core.IPythonNature)8 PyLinkedModeCompletionProposal (org.python.pydev.editor.codecompletion.proposals.PyLinkedModeCompletionProposal)8 IPyCalltipsContextInformation (org.python.pydev.editor.codefolding.IPyCalltipsContextInformation)8 File (java.io.File)7 Point (org.eclipse.swt.graphics.Point)7 OverrideMethodCompletionProposal (org.python.pydev.editor.codecompletion.proposals.OverrideMethodCompletionProposal)7 PyCompletionProposal (org.python.pydev.editor.codecompletion.proposals.PyCompletionProposal)7 IFile (org.eclipse.core.resources.IFile)6 Path (org.eclipse.core.runtime.Path)6 CompareContext (org.python.pydev.ast.codecompletion.ProposalsComparator.CompareContext)6 MisconfigurationException (org.python.pydev.core.MisconfigurationException)6