Search in sources :

Example 21 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PythonCompletionProcessor method computeCompletionProposals.

/**
 * This is the interface implemented to get the completions.
 *
 * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
 */
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    updateStatus();
    ICompletionProposalHandle[] proposals;
    try {
        // FIRST: discover activation token and qualifier.
        IDocument doc = viewer.getDocument();
        // list for storing the proposals
        TokensOrProposalsList pythonAndTemplateProposals = new TokensOrProposalsList();
        IPythonNature nature = edit.getPythonNature();
        if (nature == null) {
            IInterpreterManager manager = ChooseInterpreterManager.chooseInterpreterManager();
            if (manager != null) {
                nature = new SystemPythonNature(manager);
            } else {
                CompletionError completionError = new CompletionError(new RuntimeException("No interpreter configured."));
                this.error = completionError.getErrorMessage();
                return new ICompletionProposal[] { completionError };
            }
        }
        if (nature == null || !nature.startRequests()) {
            return new ICompletionProposal[0];
        }
        try {
            CompletionRequest request = new CompletionRequest(edit.getEditorFile(), nature, doc, documentOffset, codeCompletion, PyCodeCompletionPreferences.getUseSubstringMatchInCodeCompletion());
            // Get code completion proposals
            if (PyCodeCompletionPreferences.useCodeCompletion()) {
                if (whatToShow == SHOW_ALL) {
                    try {
                        pythonAndTemplateProposals.addAll(getPythonProposals(documentOffset, doc, request));
                    } catch (Throwable e) {
                        Log.log(e);
                        CompletionError completionError = new CompletionError(e);
                        this.error = completionError.getErrorMessage();
                        // Make the error visible to the user!
                        return new ICompletionProposal[] { completionError };
                    }
                }
            }
            String[] strs = PySelection.getActivationTokenAndQualifier(doc, documentOffset, false);
            String activationToken = strs[0];
            String qualifier = strs[1];
            // THIRD: Get template proposals (if asked for)
            if (request.showTemplates && (activationToken == null || activationToken.trim().length() == 0)) {
                TokensOrProposalsList templateProposals = getTemplateProposals(viewer, documentOffset, activationToken, qualifier);
                pythonAndTemplateProposals.addAll(templateProposals);
            }
            // to show the valid ones, we'll get the qualifier from the initial request
            proposals = PyCodeCompletionUtils.onlyValid(pythonAndTemplateProposals, request.qualifier, request.isInCalltip, request.useSubstringMatchInCodeCompletion, nature.getProject());
        // Note: sorting happens later on.
        } finally {
            nature.endRequests();
        }
    } catch (Exception e) {
        Log.log(e);
        CompletionError completionError = new CompletionError(e);
        this.error = completionError.getErrorMessage();
        // Make the error visible to the user!
        return new ICompletionProposal[] { completionError };
    }
    doCycle();
    return ConvertCompletionProposals.convertHandlesToProposals(proposals);
}
Also used : IPythonNature(org.python.pydev.core.IPythonNature) CompletionRequest(org.python.pydev.ast.codecompletion.CompletionRequest) TokensOrProposalsList(org.python.pydev.core.TokensOrProposalsList) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IInterpreterManager(org.python.pydev.core.IInterpreterManager) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) IOException(java.io.IOException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) IDocument(org.eclipse.jface.text.IDocument)

Example 22 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PySelectInterpreter method run.

@Override
public void run(IAction action) {
    try {
        PyEdit editor = getPyEdit();
        IPythonNature nature = editor.getPythonNature();
        if (nature != null) {
            IInterpreterManager interpreterManager = nature.getRelatedInterpreterManager();
            final IInterpreterInfo[] interpreterInfos = interpreterManager.getInterpreterInfos();
            if (interpreterInfos == null || interpreterInfos.length == 0) {
                PyDialogHelpers.openWarning("No interpreters available", "Unable to change default interpreter because no interpreters are available (add more interpreters in the related preferences page).");
                return;
            }
            if (interpreterInfos.length == 1) {
                PyDialogHelpers.openWarning("Only 1 interpreters available", "Unable to change default interpreter because only 1 interpreter is configured (add more interpreters in the related preferences page).");
                return;
            }
            // Ok, more than 1 found.
            IWorkbenchWindow workbenchWindow = EditorUtils.getActiveWorkbenchWindow();
            Assert.isNotNull(workbenchWindow);
            SelectionDialog listDialog = AbstractInterpreterPreferencesPage.createChooseIntepreterInfoDialog(workbenchWindow, interpreterInfos, "Select interpreter to be made the default.", false);
            int open = listDialog.open();
            if (open != ListDialog.OK || listDialog.getResult().length != 1) {
                return;
            }
            Object[] result = listDialog.getResult();
            if (result == null || result.length == 0) {
                return;
            }
            final IInterpreterInfo selectedInterpreter = ((IInterpreterInfo) result[0]);
            if (selectedInterpreter != interpreterInfos[0]) {
                // Ok, some interpreter (which wasn't already the default) was selected.
                Arrays.sort(interpreterInfos, (a, b) -> {
                    if (a == selectedInterpreter) {
                        return -1;
                    }
                    if (b == selectedInterpreter) {
                        return 1;
                    }
                    // Don't change order for the others.
                    return 0;
                });
                Shell shell = EditorUtils.getShell();
                setInterpreterInfosWithProgressDialog(interpreterManager, interpreterInfos, shell);
            }
        }
    } catch (Exception e) {
        Log.log(e);
    }
}
Also used : IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) Shell(org.eclipse.swt.widgets.Shell) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) IPythonNature(org.python.pydev.core.IPythonNature) IInterpreterManager(org.python.pydev.core.IInterpreterManager) SelectionDialog(org.eclipse.ui.dialogs.SelectionDialog) PyEdit(org.python.pydev.editor.PyEdit) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 23 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PyDocumentTemplateContext method getGrammarVersion.

public int getGrammarVersion() {
    if (this.viewer instanceof IPySourceViewer) {
        try {
            IPythonNature nature = ((IPySourceViewer) this.viewer).getEdit().getPythonNature();
            if (nature != null) {
                return nature.getGrammarVersion();
            }
        } catch (MisconfigurationException e) {
        }
    }
    if (this.viewer instanceof IScriptConsoleViewer) {
        // interactive console
        IScriptConsoleViewer v = (IScriptConsoleViewer) this.viewer;
        IInterpreterInfo interpreterInfo = (IInterpreterInfo) v.getInterpreterInfo();
        if (interpreterInfo != null) {
            return interpreterInfo.getGrammarVersion();
        }
    }
    return IGrammarVersionProvider.LATEST_GRAMMAR_PY3_VERSION;
}
Also used : IPySourceViewer(org.python.pydev.core.IPySourceViewer) IScriptConsoleViewer(org.python.pydev.core.interactive_console.IScriptConsoleViewer) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature)

Example 24 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PipPackageManager method list.

/**
 * To be called from any thread
 */
@Override
public List<String[]> list() {
    List<String[]> listed = new ArrayList<String[]>();
    File pipExecutable;
    Tuple<String, String> output;
    try {
        pipExecutable = interpreterInfo.searchExecutableForInterpreter("pip", false);
        // use system encoding
        String encoding = null;
        output = new SimpleRunner().runAndGetOutput(new String[] { pipExecutable.toString(), "list", "--format=columns" }, null, null, null, encoding);
    } catch (UnableToFindExecutableException e) {
        IPythonNature nature = new SystemPythonNature(interpreterInfo.getModulesManager().getInterpreterManager(), interpreterInfo);
        String[] parameters = SimplePythonRunner.preparePythonCallParameters(interpreterInfo.getExecutableOrJar(), "-m", new String[] { getPipModuleName(interpreterInfo), "list", "--format=columns" });
        output = new SimplePythonRunner().runAndGetOutput(parameters, null, nature, null, "utf-8");
    }
    List<String> splitInLines = StringUtils.splitInLines(output.o1, false);
    for (String line : splitInLines) {
        line = line.trim();
        List<String> split = StringUtils.split(line, ' ');
        if (split.size() == 2) {
            String p0 = split.get(0).trim();
            String p1 = split.get(1).trim();
            if (p0.toLowerCase().equals("package") && p1.toLowerCase().equals("version")) {
                continue;
            }
            if (p0.toLowerCase().startsWith("--") && p1.toLowerCase().startsWith("--")) {
                continue;
            }
            listed.add(new String[] { p0.trim(), p1.trim(), "<pip>" });
        }
    }
    if (output.o2.toLowerCase().contains("no module named pip")) {
        listed.add(new String[] { "pip not installed (or not found) in interpreter", "", "" });
    } else {
        for (String s : StringUtils.iterLines(output.o2)) {
            listed.add(new String[] { s, "", "" });
        }
    }
    return listed;
}
Also used : SimpleRunner(org.python.pydev.ast.runners.SimpleRunner) UnableToFindExecutableException(org.python.pydev.core.IInterpreterInfo.UnableToFindExecutableException) ArrayList(java.util.ArrayList) IPythonNature(org.python.pydev.core.IPythonNature) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner) File(java.io.File)

Example 25 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PythonExistingSourceFolderWizard method doCreateNew.

@Override
protected IFile doCreateNew(IProgressMonitor monitor) throws CoreException {
    IProject project = filePage.getValidatedProject();
    String name = filePage.getValidatedName();
    IPath source = filePage.getSourceToLink();
    if (project == null || !project.exists()) {
        throw new RuntimeException("The project selected does not exist in the workspace.");
    }
    IPythonPathNature pathNature = PythonNature.getPythonPathNature(project);
    if (pathNature == null) {
        IPythonNature nature = PythonNature.addNature(project, monitor, null, null, null, null, null);
        pathNature = nature.getPythonPathNature();
        if (pathNature == null) {
            throw new RuntimeException("Unable to add the nature to the seleted project.");
        }
    }
    if (source == null || !source.toFile().exists()) {
        throw new RuntimeException("The source to link to, " + source.toString() + ", does not exist.");
    }
    IFolder folder = project.getFolder(name);
    if (!folder.exists()) {
        folder.createLink(source, IResource.BACKGROUND_REFRESH, monitor);
    }
    String newPath = folder.getFullPath().toString();
    String curr = pathNature.getProjectSourcePath(true);
    if (curr == null) {
        curr = "";
    }
    if (curr.endsWith("|")) {
        curr = curr.substring(0, curr.length() - 1);
    }
    String newPathRel = PyStructureConfigHelpers.convertToProjectRelativePath(project.getFullPath().toString(), newPath);
    if (curr.length() > 0) {
        // there is already some path
        Set<String> projectSourcePathSet = pathNature.getProjectSourcePathSet(true);
        if (!projectSourcePathSet.contains(newPath)) {
            // only add to the path if it doesn't already contain the new path
            curr += "|" + newPathRel;
        }
    } else {
        // there is still no other path
        curr = newPathRel;
    }
    pathNature.setProjectSourcePath(curr);
    PythonNature.getPythonNature(project).rebuildPath();
    return null;
}
Also used : IPath(org.eclipse.core.runtime.IPath) IPythonPathNature(org.python.pydev.core.IPythonPathNature) IPythonNature(org.python.pydev.core.IPythonNature) IProject(org.eclipse.core.resources.IProject) IFolder(org.eclipse.core.resources.IFolder)

Aggregations

IPythonNature (org.python.pydev.core.IPythonNature)85 MisconfigurationException (org.python.pydev.core.MisconfigurationException)33 ArrayList (java.util.ArrayList)30 File (java.io.File)26 IProject (org.eclipse.core.resources.IProject)20 IFile (org.eclipse.core.resources.IFile)18 CoreException (org.eclipse.core.runtime.CoreException)17 Tuple (org.python.pydev.shared_core.structure.Tuple)14 IDocument (org.eclipse.jface.text.IDocument)12 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)12 ICodeCompletionASTManager (org.python.pydev.core.ICodeCompletionASTManager)11 IModule (org.python.pydev.core.IModule)10 TokensList (org.python.pydev.core.TokensList)10 HashSet (java.util.HashSet)9 List (java.util.List)9 BadLocationException (org.eclipse.jface.text.BadLocationException)9 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)9 SimpleNode (org.python.pydev.parser.jython.SimpleNode)9 PyEdit (org.python.pydev.editor.PyEdit)8 SystemPythonNature (org.python.pydev.plugin.nature.SystemPythonNature)8