Search in sources :

Example 41 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class ToggleMarkOccurrences method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ITextEditor activeEditor = EditorUtils.getActiveEditor();
    if (!(activeEditor instanceof PyEdit)) {
        return null;
    }
    PyEdit editor = (PyEdit) activeEditor;
    try {
        IPreferenceStore store = RefactoringPlugin.getDefault().getPreferenceStore();
        boolean prev = store.getBoolean(MarkOccurrencesPreferencesPage.USE_MARK_OCCURRENCES);
        store.setValue(MarkOccurrencesPreferencesPage.USE_MARK_OCCURRENCES, !prev);
        editor.getStatusLineManager().setMessage("Toggled mark occurrences. Currently: " + (prev ? "Off" : "On"));
        MarkOccurrencesJob.scheduleRequest(new WeakReference<BaseEditor>(editor), editor.createTextSelectionUtils(), // On the action, ask it to happen now.
        0);
    } catch (Exception e) {
        Log.log(e);
    }
    return null;
}
Also used : ITextEditor(org.eclipse.ui.texteditor.ITextEditor) BaseEditor(org.python.pydev.shared_ui.editor.BaseEditor) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) PyEdit(org.python.pydev.editor.PyEdit) ExecutionException(org.eclipse.core.commands.ExecutionException)

Example 42 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PythonElementHyperlinkDetector method detectHyperlinks.

/**
 * Will basically hyperlink any non keyword word (and let the PythonHyperlink work later on to open it if that's possible)
 */
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !(textEditor instanceof PyEdit)) {
        return null;
    }
    PyEdit editor = (PyEdit) textEditor;
    int offset = region.getOffset();
    try {
        IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
        // see if we can find a word there
        IRegion wordRegion = PythonWordFinder.findWord(document, offset);
        if (wordRegion == null) {
            return null;
        }
        // don't highlight keywords
        try {
            IDocument doc = editor.getDocument();
            String selectedWord = doc.get(wordRegion.getOffset(), wordRegion.getLength());
            if (PythonLanguageUtils.isKeyword(selectedWord)) {
                return null;
            }
        } catch (BadLocationException e) {
            Log.log(e);
        }
        if (wordRegion.getLength() == 0) {
            return null;
        }
        // return a hyperlink even without trying to find the definition (which may be costly)
        return new IHyperlink[] { new PythonHyperlink(wordRegion, editor) };
    } catch (Exception e) {
        Log.log(e);
        return null;
    }
}
Also used : ITextEditor(org.eclipse.ui.texteditor.ITextEditor) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) PyEdit(org.python.pydev.editor.PyEdit) IDocument(org.eclipse.jface.text.IDocument) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 43 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class MarkOccurrencesJob method createRequest.

/**
 * @return a tuple with the refactoring request, the processor and a boolean indicating if all pre-conditions succedded.
 * @throws MisconfigurationException
 */
@Override
protected MarkOccurrencesRequest createRequest(BaseEditor baseEditor, IDocumentProvider documentProvider, IProgressMonitor monitor) throws BadLocationException, OperationCanceledException, CoreException, MisconfigurationException {
    if (!MarkOccurrencesPreferencesPage.useMarkOccurrences()) {
        return new PyMarkOccurrencesRequest(false, null, null);
    }
    PyEdit pyEdit = (PyEdit) baseEditor;
    // ok, the editor is still there wit ha document... move on
    PyRefactorAction pyRefactorAction = getRefactorAction(pyEdit);
    String currToken = this.ps.getCurrToken().o1;
    if (LOCAL_TEXT_SEARCHES_ON.contains(currToken) && IDocument.DEFAULT_CONTENT_TYPE.equals(ParsingUtils.getContentType(this.ps.getDoc(), this.ps.getAbsoluteCursorOffset()))) {
        return new TextBasedLocalMarkOccurrencesRequest(currToken);
    }
    final RefactoringRequest req = getRefactoringRequest(pyEdit, pyRefactorAction, PySelection.fromTextSelection(this.ps));
    if (req == null || !req.nature.getRelatedInterpreterManager().isConfigured()) {
        // we check if it's configured because it may still be a stub...
        return new PyMarkOccurrencesRequest(false, null, null);
    }
    PyReferenceSearcher searcher = new PyReferenceSearcher(req);
    // to see if a new request was not created in the meantime (in which case this one will be cancelled)
    if (monitor.isCanceled()) {
        return new PyMarkOccurrencesRequest(false, null, null);
    }
    try {
        searcher.prepareSearch(req);
        if (monitor.isCanceled()) {
            return new PyMarkOccurrencesRequest(false, null, null);
        }
        searcher.search(req);
        if (monitor.isCanceled()) {
            return new PyMarkOccurrencesRequest(false, null, null);
        }
        // Ok, search succeeded.
        return new PyMarkOccurrencesRequest(true, req, searcher);
    } catch (PyReferenceSearcher.SearchException | BadLocationException e) {
        // Suppress search failures.
        return new PyMarkOccurrencesRequest(false, null, null);
    } catch (Throwable e) {
        throw new RuntimeException("Error in occurrences while analyzing modName:" + req.moduleName + " initialName:" + req.qualifier + " line (start at 0):" + req.ps.getCursorLine(), e);
    }
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) PyReferenceSearcher(com.python.pydev.analysis.refactoring.wizards.rename.PyReferenceSearcher) PyRefactorAction(org.python.pydev.editor.actions.refactoring.PyRefactorAction) PyEdit(org.python.pydev.editor.PyEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 44 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class ActionCreatorPyEditListener method onCreateActions.

@Override
public void onCreateActions(ListResourceBundle resources, BaseEditor baseEditor, IProgressMonitor monitor) {
    PyEdit edit = (PyEdit) baseEditor;
    edit.addOfflineActionListener("r", new PyRenameInFileAction(edit), "Rename occurrences in file", false);
    edit.addOfflineActionListener("s", new PySearchInOpenDocumentsAction(edit), "Search in open documents", true);
    edit.addOfflineActionListener("pip", new PyPipEditorAction(edit), "Execute pip actions", true);
    edit.addOfflineActionListener("pipenv", new PyPipenvEditorAction(edit), "Execute pipenv actions", true);
    edit.addOfflineActionListener("conda", new CondaEditorAction(edit), "Execute conda actions", true);
// Experimental code for creating a class derived of a class that's not public! -- depends on javassist.
// try {
// ClassLoader classLoader = IEditorStatusLine.class.getClassLoader();
// ProtectionDomain protectionDomain = IEditorStatusLine.class.getProtectionDomain();
// 
// 
// ClassPool pool = ClassPool.getDefault();
// pool.insertClassPath(new ClassClassPath(this.getClass()));
// final CtClass ctClassNew = pool.makeClass("org.eclipse.ui.texteditor.PydevFindReplaceDialog");
// 
// CtClass ctClassOriginal = pool.get("org.eclipse.ui.texteditor.FindReplaceDialog");
// ctClassNew.setModifiers(Modifier.PUBLIC);
// ctClassNew.setSuperclass(ctClassOriginal);
// 
// CtMethod afterCreateContents = CtNewMethod.make(
// "public void createContents(org.eclipse.swt.widgets.Composite parent){" +
// "super.createContents(parent);" +
// "System.out.println(\"test\");" +
// "}", ctClassNew);
// ctClassNew.addMethod(afterCreateContents);
// final Class class1 = ctClassNew.toClass(classLoader, protectionDomain);
// RunInUiThread.async(new Runnable() {
// 
// public void run() {
// Object newInstance;
// try {
// newInstance = class1.getConstructor(Shell.class).newInstance(PyAction.getShell());
// System.out.println(newInstance);
// } catch (Throwable e) {
// e.printStackTrace();
// }
// }
// });
// } catch (Exception e) {
// e.printStackTrace();//ignored
// }
// Removed because the way the action was done is not really maintainable.
// 
// // -------------------------------------------------------------------------------------
// // Find/Replace
// FindReplaceAction action = new FindReplaceAction(resources, "Editor.FindReplace.", edit);
// action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE);
// action.setId("org.python.pydev.editor.actions.findAndReplace");
// edit.setAction(ITextEditorActionConstants.FIND, action);
}
Also used : PySearchInOpenDocumentsAction(com.python.pydev.refactoring.ui.findreplace.PySearchInOpenDocumentsAction) PyEdit(org.python.pydev.editor.PyEdit)

Example 45 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PyCodeCoverageView method openFileWithCoverageMarkers.

private void openFileWithCoverageMarkers(File realFile) {
    IEditorPart editor = PyOpenEditor.doOpenEditor(realFile);
    if (editor instanceof PyEdit) {
        PyEdit e = (PyEdit) editor;
        IEditorInput input = e.getEditorInput();
        final IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
        if (original == null) {
            return;
        }
        final IDocument document = e.getDocumentProvider().getDocument(e.getEditorInput());
        // When creating it, it'll already start to listen for changes to remove the marker when needed.
        new RemoveCoverageMarkersListener(document, e, original);
        final FileNode cache = (FileNode) PyCoverage.getPyCoverage().cache.getFile(realFile);
        if (cache != null) {
            IWorkspaceRunnable r = new IWorkspaceRunnable() {

                @Override
                public void run(IProgressMonitor monitor) throws CoreException {
                    final String type = PYDEV_COVERAGE_MARKER;
                    try {
                        original.deleteMarkers(type, false, 1);
                    } catch (CoreException e1) {
                        Log.log(e1);
                    }
                    final String message = "Not Executed";
                    for (Iterator<Tuple<Integer, Integer>> it = cache.notExecutedIterator(); it.hasNext(); ) {
                        try {
                            Map<String, Object> map = new HashMap<String, Object>();
                            Tuple<Integer, Integer> startEnd = it.next();
                            IRegion region = document.getLineInformation(startEnd.o1 - 1);
                            int errorStart = region.getOffset();
                            region = document.getLineInformation(startEnd.o2 - 1);
                            int errorEnd = region.getOffset() + region.getLength();
                            map.put(IMarker.MESSAGE, message);
                            map.put(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
                            map.put(IMarker.CHAR_START, errorStart);
                            map.put(IMarker.CHAR_END, errorEnd);
                            map.put(IMarker.TRANSIENT, Boolean.valueOf(true));
                            map.put(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                            MarkerUtilities.createMarker(original, map, type);
                        } catch (Exception e1) {
                            Log.log(e1);
                        }
                    }
                }
            };
            try {
                original.getWorkspace().run(r, null, IWorkspace.AVOID_UPDATE, null);
            } catch (CoreException e1) {
                Log.log(e1);
            }
        }
    }
}
Also used : IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) IEditorPart(org.eclipse.ui.IEditorPart) IRegion(org.eclipse.jface.text.IRegion) Point(org.eclipse.swt.graphics.Point) CoreException(org.eclipse.core.runtime.CoreException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) IFileEditorInput(org.eclipse.ui.IFileEditorInput) PyEdit(org.python.pydev.editor.PyEdit) IEditorInput(org.eclipse.ui.IEditorInput) IDocument(org.eclipse.jface.text.IDocument) Tuple(org.python.pydev.shared_core.structure.Tuple)

Aggregations

PyEdit (org.python.pydev.editor.PyEdit)64 PySelection (org.python.pydev.core.docutils.PySelection)22 IFile (org.eclipse.core.resources.IFile)15 ArrayList (java.util.ArrayList)14 BadLocationException (org.eclipse.jface.text.BadLocationException)13 Path (org.eclipse.core.runtime.Path)12 IDocument (org.eclipse.jface.text.IDocument)12 MisconfigurationException (org.python.pydev.core.MisconfigurationException)9 ICompletionProposalHandle (org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)9 IPythonNature (org.python.pydev.core.IPythonNature)8 File (java.io.File)7 ICallbackListener (org.python.pydev.shared_core.callbacks.ICallbackListener)7 ByteArrayInputStream (java.io.ByteArrayInputStream)5 IRegion (org.eclipse.jface.text.IRegion)5 ITextSelection (org.eclipse.jface.text.ITextSelection)5 IEditorInput (org.eclipse.ui.IEditorInput)5 SimpleNode (org.python.pydev.parser.jython.SimpleNode)5 CoreException (org.eclipse.core.runtime.CoreException)4 RefactoringRequest (org.python.pydev.ast.refactoring.RefactoringRequest)4 IInterpreterManager (org.python.pydev.core.IInterpreterManager)4