Search in sources :

Example 51 with ITextEditor

use of org.eclipse.ui.texteditor.ITextEditor in project linuxtools by eclipse.

the class IndentHandler method execute.

@Override
public Object execute(ExecutionEvent event) {
    // the framework
    if (!isEnabled())
        return null;
    ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
    if (editor == null || !editor.isEditable()) {
        return null;
    }
    ITextSelection selection = getSelection(editor);
    final IDocument document = getDocument(editor);
    if (document != null) {
        final int offset = selection.getOffset();
        final int length = selection.getLength();
        final Position end = new Position(offset + length);
        final int firstLine, nLines;
        fCaretOffset = -1;
        try {
            firstLine = document.getLineOfOffset(offset);
            // check for marginal (zero-length) lines
            int minusOne = length == 0 ? 0 : 1;
            nLines = document.getLineOfOffset(offset + length - minusOne) - firstLine + 1;
            document.addPosition(end);
        } catch (BadLocationException e) {
            // will only happen on concurrent modification
            // $NON-NLS-1$
            IDEPlugin.log(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, IStatus.OK, "", e));
            return null;
        }
        Runnable runnable = () -> {
            IRewriteTarget target = editor.getAdapter(IRewriteTarget.class);
            if (target != null) {
                target.beginCompoundChange();
            }
            try {
                STPHeuristicScanner scanner = new STPHeuristicScanner(document);
                STPIndenter indenter = new STPIndenter(document, scanner, getProject(editor));
                final boolean multiLine = nLines > 1;
                boolean hasChanged = false;
                for (int i = 0; i < nLines; i++) {
                    hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner, multiLine);
                }
                // update caret position: move to new position when
                // indenting just one line
                // keep selection when indenting multiple
                int newOffset, newLength;
                if (!fIsTabAction && multiLine) {
                    newOffset = offset;
                    newLength = end.getOffset() - offset;
                } else {
                    newOffset = fCaretOffset;
                    newLength = 0;
                }
                // but not when we had a single line non-tab invocation
                if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length))
                    selectAndReveal(editor, newOffset, newLength);
            } catch (BadLocationException e) {
                // will only happen on concurrent modification
                IDEPlugin.log(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, IStatus.OK, "ConcurrentModification in IndentAction", // $NON-NLS-1$
                e));
            } finally {
                document.removePosition(end);
                if (target != null) {
                    target.endCompoundChange();
                }
            }
        };
        if (nLines > 50) {
            Display display = editor.getEditorSite().getWorkbenchWindow().getShell().getDisplay();
            BusyIndicator.showWhile(display, runnable);
        } else {
            runnable.run();
        }
    }
    return null;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) STPIndenter(org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPIndenter) Position(org.eclipse.jface.text.Position) IRewriteTarget(org.eclipse.jface.text.IRewriteTarget) STPHeuristicScanner(org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPHeuristicScanner) ITextSelection(org.eclipse.jface.text.ITextSelection) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) Display(org.eclipse.swt.widgets.Display)

Example 52 with ITextEditor

use of org.eclipse.ui.texteditor.ITextEditor in project linuxtools by eclipse.

the class ToggleCommentHandler method execute.

/**
 * Checks if the selected lines are all commented or not and
 * uncomments/comments them respectively.
 */
@Override
public Object execute(ExecutionEvent event) {
    ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
    if (editor == null || !editor.isEditable()) {
        return null;
    }
    updateOpTarget(editor);
    if (operationTarget == null) {
        return null;
    }
    ISelection selection = editor.getSelectionProvider().getSelection();
    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    final int operationCode;
    if (isSelectionCommented(selection, document)) {
        operationCode = ITextOperationTarget.STRIP_PREFIX;
    } else {
        operationCode = ITextOperationTarget.PREFIX;
    }
    Shell shell = editor.getSite().getShell();
    if (!operationTarget.canDoOperation(operationCode)) {
        if (shell != null) {
            MessageDialog.openError(shell, // $NON-NLS-1$
            Localization.getString("ToggleComment_error_title"), // $NON-NLS-1$
            Localization.getString("ToggleComment_error_message"));
        }
        return null;
    }
    Display display = null;
    if (shell != null && !shell.isDisposed()) {
        display = shell.getDisplay();
    }
    BusyIndicator.showWhile(display, () -> operationTarget.doOperation(operationCode));
    return null;
}
Also used : Shell(org.eclipse.swt.widgets.Shell) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) ISelection(org.eclipse.jface.viewers.ISelection) IDocument(org.eclipse.jface.text.IDocument) Display(org.eclipse.swt.widgets.Display)

Example 53 with ITextEditor

use of org.eclipse.ui.texteditor.ITextEditor in project linuxtools by eclipse.

the class SystemTapRegexGenerator method generateFromPrintf.

/**
 * Generate a list of regular expressions that will capture the output of a given .stp script.
 * Only output coming from <code>printf</code> statements will be captured.
 * @param scriptPath The absolute path of the script to capture the output of.
 * @param maxToFind The maximum number of regexs to create and return.
 * A negative value indicates no limit.
 * @return A list of generated regexs, each paired with the number of capturing groups it has.
 */
public static List<Entry<String, Integer>> generateFromPrintf(IPath scriptPath, int maxToFind) {
    List<Entry<String, Integer>> regexs = new ArrayList<>();
    if (maxToFind == 0) {
        return regexs;
    }
    String contents = null;
    IWorkbench workbench = PlatformUI.getWorkbench();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IEditorPart editor = ResourceUtil.findEditor(workbench.getActiveWorkbenchWindow().getActivePage(), root.getFile(scriptPath.makeRelativeTo(root.getLocation())));
    if (editor != null) {
        // If editor of this file is open, take current file contents.
        ITextEditor tEditor = editor.getAdapter(ITextEditor.class);
        IDocument document = tEditor.getDocumentProvider().getDocument(tEditor.getEditorInput());
        contents = CommentRemover.exec(document.get());
    } else {
        // If chosen file is not being edited or is outside of the workspace, use the saved contents of the file itself.
        contents = CommentRemover.execWithFile(scriptPath.toString());
    }
    // Now actually search the contents for "printf(...)" statements. (^|[\s({;])printf\("(.+?)",.+\)
    // $NON-NLS-1$
    Pattern pattern = Pattern.compile("(?<=[^\\w])printf\\(\"(.+?)\",.+?\\)");
    Matcher matcher = pattern.matcher(contents);
    while (matcher.find() && (maxToFind < 0 || regexs.size() < maxToFind)) {
        String regex = null;
        // Note: allow optional "long" modifier 'l'. Not captured because it doesn't impact output format.
        // Also, don't support variable width/precision modifiers (*).
        // TODO: Consider %m & %M support.
        // $NON-NLS-1$
        Pattern format = Pattern.compile("%([-\\+ \\#0])?(\\d+)?(\\.\\d*)?l?([bcdiopsuxX%])");
        // Only capture until newlines to preserve the "column" format.
        // Don't try gluing together output from multiple printfs
        // since asynchronous prints would make things messy.
        // $NON-NLS-1$
        String[] printls = matcher.group(1).split("\\\\n");
        for (int i = 0; i < printls.length; i++) {
            String printl = printls[i];
            // Ignore newlines if they are escaped ("\\n").
            if (printl.endsWith("\\")) {
                // $NON-NLS-1$
                // $NON-NLS-1$
                printls[i + 1] = printl.concat("\\n" + printls[i + 1]);
                continue;
            }
            Matcher fmatch = format.matcher(printl);
            int lastend = 0;
            int numColumns = 0;
            while (fmatch.find()) {
                numColumns++;
                char chr = fmatch.group(4) == null ? '\0' : fmatch.group(4).charAt(0);
                if (chr == '\0') {
                    // Skip this statement if an invalid regex is found.
                    regex = null;
                    break;
                }
                char flag = fmatch.group(1) == null ? '\0' : fmatch.group(1).charAt(0);
                int width = fmatch.group(2) == null ? 0 : Integer.parseInt(fmatch.group(2));
                String precision = fmatch.group(3) == null ? null : fmatch.group(3).substring(1);
                // First, add any non-capturing characters.
                String pre = addRegexEscapes(printl.substring(lastend, fmatch.start()));
                regex = lastend > 0 ? regex.concat(pre) : pre;
                lastend = fmatch.end();
                // Now add what will be captured.
                // $NON-NLS-1$
                String target = "(";
                if (chr == 'u' || (flag != '#' && chr == 'o')) {
                    // $NON-NLS-1$
                    target = target.concat("\\d+");
                } else if (chr == 'd' || chr == 'i') {
                    if (flag == '+') {
                        // $NON-NLS-1$
                        target = target.concat("\\+|");
                    } else if (flag == ' ') {
                        // $NON-NLS-1$
                        target = target.concat(" |");
                    }
                    // $NON-NLS-1$
                    target = target.concat("-?\\d+");
                } else if (flag == '#' && chr == 'o') {
                    // $NON-NLS-1$
                    target = target.concat("0\\d+");
                } else if (chr == 'p') {
                    // $NON-NLS-1$
                    target = target.concat("0x[a-f0-9]+");
                } else if (chr == 'x') {
                    if (flag == '#') {
                        // $NON-NLS-1$
                        target = target.concat("0x");
                    }
                    // $NON-NLS-1$
                    target = target.concat("[a-f0-9]+");
                } else if (chr == 'X') {
                    if (flag == '#') {
                        // $NON-NLS-1$
                        target = target.concat("0X");
                    }
                    // $NON-NLS-1$
                    target = target.concat("[A-F0-9]+");
                } else if (chr == 'b') {
                    // $NON-NLS-1$
                    target = target.concat(".");
                } else if (chr == 'c') {
                    if (flag != '#') {
                        // $NON-NLS-1$
                        target = target.concat(".");
                    } else {
                        // $NON-NLS-1$
                        target = target.concat("\\([a-z]|[0-9]{3})|.|\\\\");
                    }
                } else if (chr == 's') {
                    if (precision != null) {
                        // $NON-NLS-1$ //$NON-NLS-2$
                        target = target.concat(".{" + precision + "}");
                    } else {
                        // $NON-NLS-1$
                        target = target.concat(".+");
                    }
                } else {
                    // Invalid or unhandled format specifier. Skip this regex.
                    regex = null;
                    break;
                }
                // $NON-NLS-1$
                target = target.concat(")");
                // Ignore it for %b, which uses the width value in a different way.
                if (chr != 'b' && --width > 0) {
                    if (flag == '-') {
                        // $NON-NLS-1$ //$NON-NLS-2$
                        target = target.concat(" {0," + width + "}");
                    } else if (flag != '0' || chr == 's' || chr == 'c') {
                        // $NON-NLS-1$ //$NON-NLS-2$
                        target = " {0," + width + "}".concat(target);
                    }
                }
                regex = regex.concat(target);
            }
            if (regex != null) {
                // Finally, add the uncaptured remainder of the print statement to the regex.
                regexs.add(new SimpleEntry<>(regex.concat(addRegexEscapes(printl.substring(lastend))), numColumns));
            }
        }
    }
    return regexs;
}
Also used : Pattern(java.util.regex.Pattern) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) IEditorPart(org.eclipse.ui.IEditorPart) IWorkbench(org.eclipse.ui.IWorkbench) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) IDocument(org.eclipse.jface.text.IDocument)

Example 54 with ITextEditor

use of org.eclipse.ui.texteditor.ITextEditor in project linuxtools by eclipse.

the class DoubleClickTest method testDoubleClickFunction.

@Test
public void testDoubleClickFunction() throws Exception {
    ILaunchConfiguration config = createConfiguration(proj.getProject());
    // $NON-NLS-1$
    doLaunch(config, "testDoubleClickFunction");
    CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
    CachegrindOutput output = view.getOutputs()[0];
    // $NON-NLS-1$
    CachegrindFile file = getFileByName(output, "cpptest.cpp");
    // $NON-NLS-1$
    CachegrindFunction func = getFunctionByName(file, "main");
    TreePath path = new TreePath(new Object[] { output, file, func });
    doDoubleClick(path);
    // check file in editor
    IEditorPart editor = checkFile(file);
    // check line number
    ITextEditor textEditor = (ITextEditor) editor;
    ISelection selection = textEditor.getSelectionProvider().getSelection();
    TextSelection textSelection = (TextSelection) selection;
    // zero-indexed
    int line = textSelection.getStartLine() + 1;
    int expectedLine = ((IFunction) func.getModel()).getSourceRange().getStartLine();
    assertEquals(expectedLine, line);
}
Also used : ILaunchConfiguration(org.eclipse.debug.core.ILaunchConfiguration) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) TreePath(org.eclipse.jface.viewers.TreePath) CachegrindOutput(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindOutput) CachegrindFile(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindFile) CachegrindFunction(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindFunction) TextSelection(org.eclipse.jface.text.TextSelection) ISelection(org.eclipse.jface.viewers.ISelection) CachegrindViewPart(org.eclipse.linuxtools.internal.valgrind.cachegrind.CachegrindViewPart) IEditorPart(org.eclipse.ui.IEditorPart) Test(org.junit.Test)

Example 55 with ITextEditor

use of org.eclipse.ui.texteditor.ITextEditor in project linuxtools by eclipse.

the class DoubleClickTest method testDoubleClickLine.

@Test
public void testDoubleClickLine() throws Exception {
    ILaunchConfiguration config = createConfiguration(proj.getProject());
    // $NON-NLS-1$
    doLaunch(config, "testDoubleClickFunction");
    CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
    CachegrindOutput output = view.getOutputs()[0];
    // $NON-NLS-1$
    CachegrindFile file = getFileByName(output, "cpptest.cpp");
    // $NON-NLS-1$
    CachegrindFunction func = getFunctionByName(file, "main");
    CachegrindLine line = func.getLines()[0];
    TreePath path = new TreePath(new Object[] { output, file, func });
    doDoubleClick(path);
    // check file in editor
    IEditorPart editor = checkFile(file);
    // check line number
    ITextEditor textEditor = (ITextEditor) editor;
    ISelection selection = textEditor.getSelectionProvider().getSelection();
    TextSelection textSelection = (TextSelection) selection;
    // zero-indexed
    int actualLine = textSelection.getStartLine() + 1;
    assertEquals(line.getLine(), actualLine);
}
Also used : ILaunchConfiguration(org.eclipse.debug.core.ILaunchConfiguration) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) TreePath(org.eclipse.jface.viewers.TreePath) CachegrindOutput(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindOutput) CachegrindFile(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindFile) CachegrindFunction(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindFunction) TextSelection(org.eclipse.jface.text.TextSelection) ISelection(org.eclipse.jface.viewers.ISelection) CachegrindViewPart(org.eclipse.linuxtools.internal.valgrind.cachegrind.CachegrindViewPart) CachegrindLine(org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindLine) IEditorPart(org.eclipse.ui.IEditorPart) Test(org.junit.Test)

Aggregations

ITextEditor (org.eclipse.ui.texteditor.ITextEditor)62 IEditorPart (org.eclipse.ui.IEditorPart)27 IDocument (org.eclipse.jface.text.IDocument)24 Test (org.junit.Test)21 IWorkbenchPage (org.eclipse.ui.IWorkbenchPage)13 IDocumentProvider (org.eclipse.ui.texteditor.IDocumentProvider)12 IFile (org.eclipse.core.resources.IFile)10 BadLocationException (org.eclipse.jface.text.BadLocationException)9 ISelection (org.eclipse.jface.viewers.ISelection)9 PartInitException (org.eclipse.ui.PartInitException)9 AbstractQueuedBuildDataTest (org.eclipse.xtend.ide.tests.builder.AbstractQueuedBuildDataTest)9 StringConcatenation (org.eclipse.xtend2.lib.StringConcatenation)9 TextSelection (org.eclipse.jface.text.TextSelection)6 Annotation (org.eclipse.jface.text.source.Annotation)6 IAnnotationModel (org.eclipse.jface.text.source.IAnnotationModel)6 ILaunchConfiguration (org.eclipse.debug.core.ILaunchConfiguration)5 Position (org.eclipse.jface.text.Position)5 AbstractTextSearchResult (org.eclipse.search.ui.text.AbstractTextSearchResult)5 IWorkbench (org.eclipse.ui.IWorkbench)5 Function1 (org.eclipse.xtext.xbase.lib.Functions.Function1)5