Search in sources :

Example 21 with PyEdit

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

the class PyRemoveBlockComment method performUncommentBlock.

/**
 * Performs the action with a given PySelection
 *
 * @param ps Given PySelection
 * @return boolean The success or failure of the action
 */
public Tuple<Integer, Integer> performUncommentBlock(TextSelectionUtils ps, int startLineIndex, int endLineIndex) {
    // What we'll be replacing the selected text with
    FastStringBuffer strbuf = new FastStringBuffer();
    try {
        // discover 1st line that starts the block comment
        int i;
        IAdaptable projectAdaptable = getTextEditor();
        // For each line, uncomment it
        for (i = startLineIndex; i <= endLineIndex; i++) {
            boolean addDelim = true;
            String spacesBefore = "";
            String line = ps.getLine(i);
            int lineLen = line.length();
            for (int j = 0; j < lineLen; j++) {
                char c = line.charAt(j);
                if (c == '#') {
                    // ok, it starts with # (so, remove the whitespaces before it)
                    if (j > 0) {
                        spacesBefore = line.substring(0, j);
                    }
                    line = line.substring(j);
                    break;
                } else {
                    if (!Character.isWhitespace(c)) {
                        break;
                    }
                }
            }
            if (line.startsWith("#")) {
                line = line.substring(1);
            }
            // get the chars used in block-comments
            AbstractBlockCommentAction[] acts = new AbstractBlockCommentAction[] { new PyAddSingleBlockComment(), new PyAddBlockComment() };
            HashSet<Character> chars = new HashSet<Character>();
            for (int j = 0; j < acts.length; j++) {
                AbstractBlockCommentAction action = acts[j];
                chars.add(action.getColsAndChar(projectAdaptable).o2);
            }
            if (line.length() > 0) {
                boolean removedChar = false;
                char lastChar = '\0';
                for (int j = 0; j < line.length(); j++) {
                    lastChar = line.charAt(j);
                    if (!chars.contains(lastChar)) {
                        break;
                    } else {
                        removedChar = true;
                        line = line.substring(1);
                        j--;
                    }
                }
                if (line.length() == 0 && removedChar) {
                    addDelim = false;
                }
                if (removedChar && lastChar == ' ') {
                    line = line.substring(1);
                }
            }
            if (addDelim) {
                strbuf.append(spacesBefore);
                strbuf.append(line);
                String lineDelimiter = ps.getDoc().getLineDelimiter(i);
                if (lineDelimiter != null) {
                    strbuf.append(lineDelimiter);
                }
            }
        }
        // Ok, at this point things should be correct, but make sure than on uncomment,
        // the code goes to a proper indent position (remove spaces we may have added when creating a block).
        String string = strbuf.toString();
        List<String> lines = StringUtils.splitInLines(string);
        Tuple<Integer, String> posAndLine = new Tuple<Integer, String>(-1, "");
        for (String line : lines) {
            // Don't consider empty lines
            if (line.trim().length() > 0) {
                int firstCharPosition = PySelection.getFirstCharPosition(line);
                if (firstCharPosition < posAndLine.o1 || posAndLine.o1 < 0) {
                    posAndLine.o1 = firstCharPosition;
                    posAndLine.o2 = line;
                }
            }
        }
        if (posAndLine.o1 > 0) {
            String sub = posAndLine.o2.substring(0, posAndLine.o1);
            if (sub.endsWith("\t") && sub.startsWith(" ")) {
                for (int j = 0; j < sub.length(); j++) {
                    if (Character.isWhitespace(sub.charAt(j)) && sub.charAt(j) != '\t') {
                    } else {
                        sub = sub.substring(0, j);
                    }
                }
            }
            if (sub.endsWith(" ")) {
                // If it ends with a tab, we won't change anything (only spaces are removed -- which we may have introduced)
                boolean allEqual = true;
                for (String line : lines) {
                    if (!line.startsWith(sub)) {
                        // Don't consider empty lines
                        if (line.trim().length() > 0) {
                            allEqual = false;
                        }
                        break;
                    }
                }
                if (allEqual) {
                    if (sub.startsWith("\t")) {
                        // Tabs based indent: remove any ending spaces (and at this point we know a string ends with a space)
                        int j;
                        for (j = sub.length() - 1; j >= 0; j--) {
                            char c = sub.charAt(j);
                            if (c != ' ') {
                                j++;
                                break;
                            }
                        }
                        String newSub = sub.substring(0, j);
                        strbuf.clear();
                        for (String line : lines) {
                            strbuf.append(newSub);
                            strbuf.append(line.substring(sub.length()));
                        }
                    } else {
                        IIndentPrefs indentPrefs;
                        if (targetEditor instanceof PyEdit) {
                            PyEdit pyEdit = (PyEdit) targetEditor;
                            indentPrefs = pyEdit.getIndentPrefs();
                        } else {
                            indentPrefs = DefaultIndentPrefs.get(null);
                        }
                        String indentationString = indentPrefs.getIndentationString();
                        if (indentationString.equals("\t")) {
                            strbuf.clear();
                            for (String line : lines) {
                                if (line.startsWith(sub)) {
                                    // must check as we may have empty lines
                                    strbuf.append(line.substring(sub.length()));
                                } else {
                                    strbuf.append(line);
                                }
                            }
                        } else {
                            int subLen = sub.length();
                            int indentLen = indentationString.length();
                            int mod = subLen % indentLen;
                            if (mod != 0) {
                                String substring = sub.substring(subLen - mod, subLen);
                                boolean onlyWhitespaces = true;
                                for (int k = 0; k < substring.length(); k++) {
                                    if (substring.charAt(k) != ' ') {
                                        onlyWhitespaces = false;
                                        break;
                                    }
                                }
                                if (onlyWhitespaces) {
                                    String newSub = sub.substring(0, subLen - mod);
                                    strbuf.clear();
                                    for (String line : lines) {
                                        if (line.trim().length() == 0) {
                                            strbuf.append(line);
                                        } else {
                                            strbuf.append(newSub);
                                            strbuf.append(line.substring(sub.length()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Replace the text with the modified information
        int startLineOffset = ps.getLineOffset(startLineIndex);
        int endLineOffset = ps.getEndLineOffset(endLineIndex);
        String endLineDelimiter = ps.getDoc().getLineDelimiter(endLineIndex);
        int endLen = 0;
        if (endLineDelimiter != null) {
            endLen = endLineDelimiter.length();
            endLineOffset += endLen;
        }
        String str = strbuf.toString();
        ps.getDoc().replace(startLineOffset, endLineOffset - startLineOffset, str);
        int len = str.length();
        if (len > endLen) {
            len -= endLen;
        }
        return new Tuple<Integer, Integer>(startLineOffset, len);
    } catch (Exception e) {
        beep(e);
    }
    // In event of problems, return null
    return null;
}
Also used : IAdaptable(org.eclipse.core.runtime.IAdaptable) FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) IIndentPrefs(org.python.pydev.core.IIndentPrefs) Tuple(org.python.pydev.shared_core.structure.Tuple) PyEdit(org.python.pydev.editor.PyEdit) HashSet(java.util.HashSet)

Example 22 with PyEdit

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

the class PyRefactorAction method getRefactoringRequest.

/**
 * @return the refactoring request (it is created and cached if still not available)
 * @throws MisconfigurationException
 */
public RefactoringRequest getRefactoringRequest(IProgressMonitor monitor) throws MisconfigurationException {
    if (request == null) {
        // testing first with whole lines.
        // may not be available in tests, that's why it is important to be able to operate without it
        PyEdit pyEdit = getPyEdit();
        request = createRefactoringRequest(monitor, pyEdit, ps);
    }
    request.pushMonitor(monitor);
    return request;
}
Also used : PyEdit(org.python.pydev.editor.PyEdit)

Example 23 with PyEdit

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

the class PyMoveImportsToLocalCompletionProposal method apply.

@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    IDocument doc = viewer.getDocument();
    apply(doc);
    if (forceReparseOnApply) {
        // and after applying it, let's request a reanalysis
        if (viewer instanceof PySourceViewer) {
            PySourceViewer sourceViewer = (PySourceViewer) viewer;
            PyEdit edit = sourceViewer.getEdit();
            if (edit != null) {
                edit.getParser().forceReparse(new Tuple<String, Boolean>(IMiscConstants.ANALYSIS_PARSER_OBSERVER_FORCE, true));
            }
        }
    }
}
Also used : PySourceViewer(org.python.pydev.editor.codefolding.PySourceViewer) IDocument(org.eclipse.jface.text.IDocument) PyEdit(org.python.pydev.editor.PyEdit)

Example 24 with PyEdit

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

the class PyComment method run.

/**
 * Grabs the selection information and performs the action.
 */
@Override
public void run(IAction action) {
    try {
        if (!canModifyEditor()) {
            return;
        }
        PyEdit pyEdit = getPyEdit();
        this.std = pyEdit.getFormatStd();
        TextSelectionUtils ps = EditorUtils.createTextSelectionUtils(pyEdit);
        // Perform the action
        IAdaptable projectAdaptable = getTextEditor();
        String commentOption = PyScopedPreferences.getString(CommentBlocksPreferences.ADD_COMMENTS_OPTION, projectAdaptable);
        Tuple<Integer, Integer> repRegion = perform(ps, commentOption);
        // Put cursor at the first area of the selection
        pyEdit.selectAndReveal(repRegion.o1, repRegion.o2);
    } catch (Exception e) {
        beep(e);
    }
}
Also used : IAdaptable(org.eclipse.core.runtime.IAdaptable) TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) PyEdit(org.python.pydev.editor.PyEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 25 with PyEdit

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

the class PyFormatAction method run.

/**
 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
 */
@Override
public void run(IAction action) {
    try {
        if (!canModifyEditor()) {
            return;
        }
        PyEdit pyEdit = getPyEdit();
        PySelection ps = PySelectionFromEditor.createPySelectionFromEditor(pyEdit);
        try {
            int[] regionsToFormat = null;
            if (ps.getSelLength() > 0) {
                int startLineIndex = ps.getStartLineIndex();
                int endLineIndex = ps.getEndLineIndex();
                regionsToFormat = new int[endLineIndex - startLineIndex + 1];
                for (int i = startLineIndex, j = 0; i <= endLineIndex; i++, j++) {
                    regionsToFormat[j] = i;
                }
            } else {
                // For full-formatting, we cannot have a syntax error.
                if (pyEdit.hasSyntaxError(ps.getDoc())) {
                    return;
                }
            }
            applyFormatAction(pyEdit, ps, regionsToFormat, true, pyEdit.getSelectionProvider());
        } catch (SyntaxErrorException e) {
            pyEdit.getStatusLineManager().setErrorMessage(e.getMessage());
        }
    } catch (Exception e) {
        beep(e);
    }
}
Also used : SyntaxErrorException(org.python.pydev.core.docutils.SyntaxErrorException) PySelection(org.python.pydev.core.docutils.PySelection) PyEdit(org.python.pydev.editor.PyEdit) SyntaxErrorException(org.python.pydev.core.docutils.SyntaxErrorException) BadLocationException(org.eclipse.jface.text.BadLocationException)

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