Search in sources :

Example 1 with TextSelectionUtils

use of org.python.pydev.shared_core.string.TextSelectionUtils in project Pydev by fabioz.

the class PyAutoIndentStrategy method handleLiteral.

/**
 * Called right after a ' or "
 */
private void handleLiteral(IDocument document, IDocumentCommand command, boolean isDefaultContext, char literalChar) {
    if (!prefs.getAutoLiterals()) {
        return;
    }
    TextSelectionUtils ps = new TextSelectionUtils(document, new CoreTextSelection(document, command.getOffset(), command.getLength()));
    if (command.getLength() > 0) {
        try {
            // We have more contents selected. Delete it so that we can properly use the heuristics.
            ps.deleteSelection();
            command.setLength(0);
            ps.setSelection(command.getOffset(), command.getOffset());
        } catch (BadLocationException e) {
        }
    }
    try {
        char nextChar = ps.getCharAfterCurrentOffset();
        if (Character.isJavaIdentifierPart(nextChar)) {
            // e.g. |var (| is cursor position)
            return;
        }
    } catch (BadLocationException e) {
    }
    String cursorLineContents = ps.getCursorLineContents();
    if (cursorLineContents.indexOf(literalChar) == -1) {
        if (!isDefaultContext) {
            // only add additional chars if on default context.
            return;
        }
        command.setText(StringUtils.getWithClosedPeer(literalChar));
        command.setShiftsCaret(false);
        command.setCaretOffset(command.getOffset() + 1);
        return;
    }
    boolean balanced = isLiteralBalanced(cursorLineContents);
    Tuple<String, String> beforeAndAfterMatchingChars = ps.getBeforeAndAfterMatchingChars(literalChar);
    int matchesBefore = beforeAndAfterMatchingChars.o1.length();
    int matchesAfter = beforeAndAfterMatchingChars.o2.length();
    boolean hasMatchesBefore = matchesBefore != 0;
    boolean hasMatchesAfter = matchesAfter != 0;
    if (!hasMatchesBefore && !hasMatchesAfter) {
        // if it's not balanced, this char would be the closing char.
        if (balanced) {
            if (!isDefaultContext) {
                // only add additional chars if on default context.
                return;
            }
            command.setText(StringUtils.getWithClosedPeer(literalChar));
            command.setShiftsCaret(false);
            command.setCaretOffset(command.getOffset() + 1);
        }
    } else {
        if (matchesAfter == 1) {
            // just walk the caret
            command.setText("");
            command.setShiftsCaret(false);
            command.setCaretOffset(command.getOffset() + 1);
        }
    }
}
Also used : TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) CoreTextSelection(org.python.pydev.shared_core.string.CoreTextSelection) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 2 with TextSelectionUtils

use of org.python.pydev.shared_core.string.TextSelectionUtils in project Pydev by fabioz.

the class StepIntoSelectionHyperlinkDetector method detectHyperlinks.

/**
 * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
 */
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    ITextEditor editor = getAdapter(ITextEditor.class);
    if (editor instanceof PyEdit) {
        PyEdit pyEdit = (PyEdit) editor;
        // should only enable step into selection when the current debug context
        // is an instance of IJavaStackFrame
        IAdaptable debugContext = DebugUITools.getDebugContext();
        if (debugContext == null) {
            return null;
        }
        if (!(debugContext instanceof PyStackFrame)) {
            return null;
        }
        PyStackFrame pyStackFrame = (PyStackFrame) debugContext;
        SmartStepIntoVariant[] stepIntoTargets = pyStackFrame.getStepIntoTargets();
        if (stepIntoTargets == null) {
            Log.log("Unable to get Smart Step Into Targets.");
            return null;
        }
        int offset = region.getOffset();
        try {
            IDocument document = pyEdit.getDocument();
            // see if we can find a word there
            IRegion wordRegion = TextSelectionUtils.findWord(document, offset);
            if (wordRegion == null || wordRegion.getLength() == 0) {
                return null;
            }
            String selectedWord;
            // don't highlight keywords
            try {
                selectedWord = document.get(wordRegion.getOffset(), wordRegion.getLength());
                if (PythonLanguageUtils.isKeyword(selectedWord)) {
                    return null;
                }
            } catch (BadLocationException e) {
                Log.log(e);
                return null;
            }
            ICoreTextSelection textSelection = pyEdit.getTextSelection();
            int line = textSelection.getStartLine();
            List<SmartStepIntoVariant> found = new ArrayList<>();
            for (SmartStepIntoVariant smartStepIntoVariant : stepIntoTargets) {
                if (line == smartStepIntoVariant.line && selectedWord.equals(smartStepIntoVariant.name)) {
                    found.add(smartStepIntoVariant);
                }
            }
            if (found.size() == 0) {
                Log.log("Unable to find step into target with name: " + selectedWord + " at line: " + line + "\nAvailable: " + StringUtils.join("; ", stepIntoTargets));
                return null;
            }
            SmartStepIntoVariant target;
            if (found.size() > 1) {
                // i.e.: the target is backwards.
                Collections.reverse(found);
                Iterator<SmartStepIntoVariant> iterator = found.iterator();
                target = iterator.next();
                TextSelectionUtils ts = new TextSelectionUtils(document, textSelection);
                // Let's check if there's more than one occurrence of the same word in the given line.
                String lineContents = ts.getLine(line);
                List<Integer> wordOffsets = StringUtils.findWordOffsets(lineContents, selectedWord);
                if (wordOffsets.size() > 0) {
                    int offsetInLine = wordRegion.getOffset() - ts.getStartLineOffset();
                    for (Integer i : wordOffsets) {
                        if (i >= offsetInLine) {
                            break;
                        }
                        target = iterator.next();
                        if (!iterator.hasNext()) {
                            break;
                        }
                    }
                }
            } else {
                // size == 1
                target = found.get(0);
            }
            // return a hyperlink even without trying to find the definition (which may be costly)
            return new IHyperlink[] { new StepIntoSelectionHyperlink((PyStackFrame) debugContext, pyEdit, wordRegion, line, selectedWord, target) };
        } catch (Exception e) {
            Log.log(e);
            return null;
        }
    }
    return null;
}
Also used : IAdaptable(org.eclipse.core.runtime.IAdaptable) PyStackFrame(org.python.pydev.debug.model.PyStackFrame) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) SmartStepIntoVariant(org.python.pydev.debug.model.SmartStepIntoVariant) ArrayList(java.util.ArrayList) ICoreTextSelection(org.python.pydev.shared_core.string.ICoreTextSelection) IRegion(org.eclipse.jface.text.IRegion) DebugException(org.eclipse.debug.core.DebugException) BadLocationException(org.eclipse.jface.text.BadLocationException) TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) PyEdit(org.python.pydev.editor.PyEdit) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 3 with TextSelectionUtils

use of org.python.pydev.shared_core.string.TextSelectionUtils in project Pydev by fabioz.

the class ScriptConsoleDocumentListener method addToConsoleView.

/**
 * Adds some text that came as an output to stdout or stderr to the console.
 *
 * @param out the text that should be added
 * @param stdout true if it came from stdout and also if it came from stderr
 */
private void addToConsoleView(String out, boolean stdout, boolean textAddedIsReadOnly) {
    if (out.length() == 0) {
        // nothing to add!
        return;
    }
    int start = doc.getLength();
    IConsoleStyleProvider styleProvider = viewer.getStyleProvider();
    Tuple<List<ScriptStyleRange>, String> style = null;
    if (styleProvider != null) {
        if (stdout) {
            style = styleProvider.createInterpreterOutputStyle(out, start);
        } else {
            // stderr
            style = styleProvider.createInterpreterErrorStyle(out, start);
        }
        if (style != null) {
            for (ScriptStyleRange s : style.o1) {
                addToPartitioner(s);
            }
        }
    }
    if (style != null) {
        appendText(style.o2);
        if (textAddedIsReadOnly) {
            try {
                // The text we just appended can't be changed!
                int lastLine = doc.getNumberOfLines() - 1;
                int len = doc.getLineLength(lastLine);
                this.readOnlyColumnsInCurrentBeforePrompt = len;
            } catch (BadLocationException e) {
                Log.log(e);
            }
        }
    }
    TextSelectionUtils ps = new TextSelectionUtils(doc, start);
    int cursorLine = ps.getCursorLine();
    int numberOfLines = doc.getNumberOfLines();
    // right after appending the text, let's notify line trackers
    for (int i = cursorLine; i < numberOfLines; i++) {
        try {
            int offset = ps.getLineOffset(i);
            int endOffset = ps.getEndLineOffset(i);
            Region region = new Region(offset, endOffset - offset);
            for (IConsoleLineTracker lineTracker : this.consoleLineTrackers) {
                lineTracker.lineAppended(region);
            }
        } catch (Exception e) {
            Log.log(e);
        }
    }
    if (!this.scrollLock) {
        revealEndOfDocument();
    }
}
Also used : IConsoleStyleProvider(org.python.pydev.shared_interactive_console.console.ui.IConsoleStyleProvider) TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) Region(org.eclipse.jface.text.Region) ArrayList(java.util.ArrayList) List(java.util.List) IConsoleLineTracker(org.eclipse.debug.ui.console.IConsoleLineTracker) ScriptStyleRange(org.python.pydev.shared_interactive_console.console.ui.ScriptStyleRange) BadLocationException(org.eclipse.jface.text.BadLocationException) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 4 with TextSelectionUtils

use of org.python.pydev.shared_core.string.TextSelectionUtils in project Pydev by fabioz.

the class HandleLineStartAction method execute.

/**
 * When going to the line start, we must actually go to: 1st char / prompt end / line start (depending
 * on where we are currently)
 *
 * @return true if it was done and false otherwise.
 */
public boolean execute(IDocument doc, int caretOffset, int commandLineOffset, IScriptConsoleViewer viewer) {
    try {
        TextSelectionUtils ps = new TextSelectionUtils(doc, caretOffset);
        int lineOffset = ps.getLineOffset();
        int promptEndOffset = lineOffset;
        ScriptConsolePartitioner partitioner = (ScriptConsolePartitioner) doc.getDocumentPartitioner();
        int docLen = doc.getLength();
        for (; promptEndOffset < docLen; promptEndOffset++) {
            ScriptStyleRange[] range = partitioner.getStyleRanges(promptEndOffset, 1);
            if (range.length >= 1) {
                if (range[0].scriptType != ScriptStyleRange.PROMPT) {
                    break;
                }
            }
        }
        int absoluteCursorOffset = ps.getAbsoluteCursorOffset();
        IRegion lineInformation = doc.getLineInformationOfOffset(absoluteCursorOffset);
        String contentsFromPrompt = doc.get(promptEndOffset, lineInformation.getOffset() + lineInformation.getLength() - promptEndOffset);
        int firstCharPosition = TextSelectionUtils.getFirstCharPosition(contentsFromPrompt);
        int firstCharOffset = promptEndOffset + firstCharPosition;
        // 1st see: if we're in the start of the line, go to the 1st char after the prompt
        if (lineOffset == absoluteCursorOffset || firstCharOffset < absoluteCursorOffset) {
            viewer.setCaretOffset(firstCharOffset, false);
            return true;
        }
        if (promptEndOffset < absoluteCursorOffset) {
            viewer.setCaretOffset(promptEndOffset, false);
            return true;
        }
        viewer.setCaretOffset(lineOffset, false);
        return true;
    } catch (BadLocationException e) {
        Log.log(e);
    }
    return false;
}
Also used : TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) ScriptConsolePartitioner(org.python.pydev.shared_interactive_console.console.ui.ScriptConsolePartitioner) ScriptStyleRange(org.python.pydev.shared_interactive_console.console.ui.ScriptStyleRange) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 5 with TextSelectionUtils

use of org.python.pydev.shared_core.string.TextSelectionUtils in project Pydev by fabioz.

the class CommentActionTest method createTextSelectionUtils.

private TextSelectionUtils createTextSelectionUtils(String content, int startLine) {
    TextSelectionUtils ts = new TextSelectionUtils(new Document(content), 0);
    int startOffset = ts.getLineOffset(startLine);
    ts.setSelection(startOffset, content.length() + 1);
    return ts;
}
Also used : TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) Document(org.eclipse.jface.text.Document)

Aggregations

TextSelectionUtils (org.python.pydev.shared_core.string.TextSelectionUtils)10 BadLocationException (org.eclipse.jface.text.BadLocationException)6 IRegion (org.eclipse.jface.text.IRegion)3 CoreTextSelection (org.python.pydev.shared_core.string.CoreTextSelection)3 ArrayList (java.util.ArrayList)2 IAdaptable (org.eclipse.core.runtime.IAdaptable)2 IDocument (org.eclipse.jface.text.IDocument)2 PyEdit (org.python.pydev.editor.PyEdit)2 ICoreTextSelection (org.python.pydev.shared_core.string.ICoreTextSelection)2 ScriptStyleRange (org.python.pydev.shared_interactive_console.console.ui.ScriptStyleRange)2 List (java.util.List)1 DebugException (org.eclipse.debug.core.DebugException)1 IConsoleLineTracker (org.eclipse.debug.ui.console.IConsoleLineTracker)1 Document (org.eclipse.jface.text.Document)1 ITextSelection (org.eclipse.jface.text.ITextSelection)1 Region (org.eclipse.jface.text.Region)1 IHyperlink (org.eclipse.jface.text.hyperlink.IHyperlink)1 ISelection (org.eclipse.jface.viewers.ISelection)1 ISelectionProvider (org.eclipse.jface.viewers.ISelectionProvider)1 ITextEditor (org.eclipse.ui.texteditor.ITextEditor)1