Search in sources :

Example 1 with PyFormatAction

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

the class ImportArranger method perform.

/**
 * @param executeOnlyIfChanged: if 'true' initially, we'll check if something changes first. If something changes
 * it'll call itself again with 'false' to force the changes.
 */
private void perform(boolean groupFromImports, boolean executeOnlyIfChanged, IPyFormatStdProvider edit) {
    List<Tuple3<Integer, String, ImportHandle>> list = collectImports();
    if (list.isEmpty()) {
        return;
    }
    int lineOfFirstOldImport = list.get(0).o1;
    List<Tuple<Integer, String>> linesToDelete = deleteImports(list);
    if (!executeOnlyIfChanged) {
        for (Tuple<Integer, String> tup : linesToDelete) {
            PySelection.deleteLine(doc, tup.o1);
        }
    }
    lineForNewImports = insertImportsHere(lineOfFirstOldImport);
    if (this.removeUnusedImports) {
        pruneEmptyImports(list);
    }
    sortImports(list);
    // now, re-add the imports
    String finalStr = createImportsStr(groupFromImports, list);
    if (executeOnlyIfChanged) {
        // If going automatic, let's check the contents before actually doing the organize
        // (and skip if the order is ok).
        ArrayList<String> list2 = new ArrayList<String>();
        for (Tuple<Integer, String> tup : linesToDelete) {
            list2.add(tup.o2);
        }
        Collections.reverse(list2);
        String join = StringUtils.join("", list2).trim();
        String other = StringUtils.replaceNewLines(finalStr, "").trim();
        if (join.equals(other)) {
        // System.out.println("Equals");
        } else {
            // System.out.println("Not equal!");
            // System.out.println("\n\n---");
            // System.out.println(join);
            // System.out.println("---");
            // System.out.println(other);
            // System.out.println("---\n");
            perform(groupFromImports, false, edit);
        }
        return;
    }
    try {
        PyFormatAction std = new PyFormatAction();
        boolean throwSyntaxError = false;
        ISelectionProvider selectionProvider = null;
        int[] regionsToFormat = null;
        IDocument psDoc = new Document(finalStr);
        PySelection ps = new PySelection(psDoc);
        std.applyFormatAction(edit, ps, regionsToFormat, throwSyntaxError, selectionProvider);
        finalStr = psDoc.get();
        if (addNewLinesToImports) {
            // Leave 2 empty new lines separating imports from code
            String expectedEnd = endLineDelim + endLineDelim + endLineDelim;
            while (!finalStr.endsWith(expectedEnd)) {
                finalStr += endLineDelim;
            }
        }
    } catch (Exception e) {
        Log.log(e);
    }
    PySelection.addLine(doc, endLineDelim, finalStr, lineForNewImports);
}
Also used : ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) Tuple3(org.python.pydev.shared_core.structure.Tuple3) PySelection(org.python.pydev.core.docutils.PySelection) PyFormatAction(org.python.pydev.editor.actions.PyFormatAction) Tuple(org.python.pydev.shared_core.structure.Tuple) IDocument(org.eclipse.jface.text.IDocument)

Example 2 with PyFormatAction

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

the class PyEdit method performSave.

/**
 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
 */
@Override
protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
    final IDocument document = getDocument();
    boolean keepOn;
    try {
        keepOn = true;
        if (PydevSaveActionsPrefPage.getAutoformatOnlyWorkspaceFiles(this)) {
            if (getIFile() == null) {
                // not a workspace file and user has chosen to only auto-format workspace files.
                keepOn = false;
            }
        }
    } catch (Exception e1) {
        Log.log(e1);
        // Shouldn't happen: let's skip the save actions...
        keepOn = false;
    }
    // Save actions before code-formatting (so that we apply the formatting to it afterwards).
    try {
        if (keepOn) {
            executeSaveActions(document);
        }
    } catch (final Throwable e) {
        Log.log(e);
    }
    // Before saving, let's see if the auto-code formatting is turned on.
    try {
        // TODO CYTHON: support code-formatter.
        if (keepOn && PydevSaveActionsPrefPage.getFormatBeforeSaving(this) && !isCythonFile()) {
            IStatusLineManager statusLineManager = this.getStatusLineManager();
            IDocumentProvider documentProvider = getDocumentProvider();
            int[] regionsForSave = null;
            if (PyFormatterPreferences.getFormatOnlyChangedLines(this)) {
                if (documentProvider instanceof PyDocumentProvider) {
                    PyDocumentProvider pyDocumentProvider = (PyDocumentProvider) documentProvider;
                    ITextFileBuffer fileBuffer = pyDocumentProvider.getFileBuffer(getEditorInput());
                    if (fileBuffer != null) {
                        regionsForSave = ChangedLinesComputer.calculateChangedLines(fileBuffer, progressMonitor == null ? new NullProgressMonitor() : progressMonitor);
                    }
                } else {
                    Log.log("Was expecting PyDocumentProvider. Found: " + documentProvider);
                }
            }
            if (regionsForSave == null || regionsForSave.length > 0) {
                // Note: auto-format should only take place if we're always formatting everything or
                // if we have some region to update (regionsForSave.length == 0 means that we only
                // had deleted lines, in which case we can't really do anything).
                PySelection ps = new PySelection(document, this.getTextSelection());
                if (!hasSyntaxError(ps.getDoc())) {
                    PyFormatAction std = new PyFormatAction();
                    boolean throwSyntaxError = true;
                    try {
                        std.applyFormatAction(this, ps, regionsForSave, throwSyntaxError, this.getSelectionProvider());
                        statusLineManager.setErrorMessage(null);
                    } catch (SyntaxErrorException e) {
                        statusLineManager.setErrorMessage(e.getMessage());
                    }
                }
            }
        }
    } catch (Throwable e) {
        // can never fail
        Log.log(e);
    }
    try {
        fixEncoding(getEditorInput(), document);
    } catch (Throwable e) {
        // can never fail
        Log.log(e);
    }
    // will provide notifications
    super.performSave(overwrite, progressMonitor);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatusLineManager(org.eclipse.jface.action.IStatusLineManager) SyntaxErrorException(org.python.pydev.core.docutils.SyntaxErrorException) CoreException(org.eclipse.core.runtime.CoreException) PartInitException(org.eclipse.ui.PartInitException) SyntaxErrorException(org.python.pydev.core.docutils.SyntaxErrorException) BadLocationException(org.eclipse.jface.text.BadLocationException) DeviceResourceException(org.eclipse.jface.resource.DeviceResourceException) NotConfiguredInterpreterException(org.python.pydev.core.NotConfiguredInterpreterException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ParseException(org.python.pydev.parser.jython.ParseException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IDocumentProvider(org.eclipse.ui.texteditor.IDocumentProvider) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) PySelection(org.python.pydev.core.docutils.PySelection) PyFormatAction(org.python.pydev.editor.actions.PyFormatAction) IDocument(org.eclipse.jface.text.IDocument)

Aggregations

IDocument (org.eclipse.jface.text.IDocument)2 PySelection (org.python.pydev.core.docutils.PySelection)2 PyFormatAction (org.python.pydev.editor.actions.PyFormatAction)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ArrayList (java.util.ArrayList)1 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)1 CoreException (org.eclipse.core.runtime.CoreException)1 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1 IStatusLineManager (org.eclipse.jface.action.IStatusLineManager)1 DeviceResourceException (org.eclipse.jface.resource.DeviceResourceException)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1 Document (org.eclipse.jface.text.Document)1 ISelectionProvider (org.eclipse.jface.viewers.ISelectionProvider)1 PartInitException (org.eclipse.ui.PartInitException)1 IDocumentProvider (org.eclipse.ui.texteditor.IDocumentProvider)1 MisconfigurationException (org.python.pydev.core.MisconfigurationException)1 NotConfiguredInterpreterException (org.python.pydev.core.NotConfiguredInterpreterException)1 SyntaxErrorException (org.python.pydev.core.docutils.SyntaxErrorException)1 ParseException (org.python.pydev.parser.jython.ParseException)1 Tuple (org.python.pydev.shared_core.structure.Tuple)1