Search in sources :

Example 1 with Region

use of org.eclipse.jface.text.Region in project che by eclipse.

the class JavaWordFinder method findWord.

public static IRegion findWord(IDocument document, int offset) {
    int start = -2;
    int end = -1;
    try {
        int pos = offset;
        char c;
        while (pos >= 0) {
            c = document.getChar(pos);
            if (!Character.isJavaIdentifierPart(c)) {
                // Check for surrogates
                if (isSurrogate(c)) {
                /*
						 * XXX: Here we should create the code point and test whether
						 * it is a Java identifier part. Currently this is not possible
						 * because java.lang.Character in 1.4 does not support surrogates
						 * and because com.ibm.icu.lang.UCharacter.isJavaIdentifierPart(int)
						 * is not correctly implemented.
						 */
                } else {
                    break;
                }
            }
            --pos;
        }
        start = pos;
        pos = offset;
        int length = document.getLength();
        while (pos < length) {
            c = document.getChar(pos);
            if (!Character.isJavaIdentifierPart(c)) {
                if (isSurrogate(c)) {
                /*
						 * XXX: Here we should create the code point and test whether
						 * it is a Java identifier part. Currently this is not possible
						 * because java.lang.Character in 1.4 does not support surrogates
						 * and because com.ibm.icu.lang.UCharacter.isJavaIdentifierPart(int)
						 * is not correctly implemented.
						 */
                } else {
                    break;
                }
            }
            ++pos;
        }
        end = pos;
    } catch (BadLocationException x) {
    }
    if (start >= -1 && end > -1) {
        if (start == offset && end == offset) {
            try {
                char c = document.getChar(offset);
                switch(c) {
                    case '-':
                        if (document.getChar(offset + 1) == '>') {
                            return new Region(offset, 2);
                        }
                        break;
                    case '>':
                        if (document.getChar(offset - 1) == '-') {
                            return new Region(offset - 1, 2);
                        }
                        break;
                    case ':':
                        if (document.getChar(offset + 1) == ':') {
                            return new Region(offset, 2);
                        } else if (document.getChar(offset - 1) == ':') {
                            return new Region(offset - 1, 2);
                        }
                        break;
                }
            } catch (BadLocationException e) {
            }
            return new Region(offset, 0);
        } else if (start == offset) {
            //XXX: probably unused...
            return new Region(start, end - start);
        } else {
            return new Region(start + 1, end - start - 1);
        }
    }
    return null;
}
Also used : Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 2 with Region

use of org.eclipse.jface.text.Region in project che by eclipse.

the class FlowAnalyzer method createSwitchData.

//---- Helper to process switch statement ----------------------------------------
protected SwitchData createSwitchData(SwitchStatement node) {
    SwitchData result = new SwitchData();
    List<Statement> statements = node.statements();
    if (statements.isEmpty())
        return result;
    int start = -1, end = -1;
    GenericSequentialFlowInfo info = null;
    for (Iterator<Statement> iter = statements.iterator(); iter.hasNext(); ) {
        Statement statement = iter.next();
        if (statement instanceof SwitchCase) {
            SwitchCase switchCase = (SwitchCase) statement;
            if (switchCase.isDefault()) {
                result.setHasDefaultCase();
            }
            if (info == null) {
                info = createSequential();
                start = statement.getStartPosition();
            } else {
                if (info.isReturn() || info.isPartialReturn() || info.branches()) {
                    result.add(new Region(start, end - start + 1), info);
                    info = createSequential();
                    start = statement.getStartPosition();
                }
            }
        } else {
            info.merge(getFlowInfo(statement), fFlowContext);
        }
        end = statement.getStartPosition() + statement.getLength() - 1;
    }
    result.add(new Region(start, end - start + 1), info);
    return result;
}
Also used : Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion)

Example 3 with Region

use of org.eclipse.jface.text.Region in project che by eclipse.

the class SelectionAnalyzer method getSelectedNodeRange.

public IRegion getSelectedNodeRange() {
    if (fSelectedNodes == null || fSelectedNodes.isEmpty())
        return null;
    ASTNode firstNode = fSelectedNodes.get(0);
    ASTNode lastNode = fSelectedNodes.get(fSelectedNodes.size() - 1);
    int start = firstNode.getStartPosition();
    return new Region(start, lastNode.getStartPosition() + lastNode.getLength() - start);
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion)

Example 4 with Region

use of org.eclipse.jface.text.Region in project che by eclipse.

the class MultiStateTextFileChange method getPreviewContent.

/*
	 * @see org.eclipse.ltk.core.refactoring.TextEditBasedChange#getPreviewContent(org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup[],org.eclipse.jface.text.IRegion,boolean,int,org.eclipse.core.runtime.IProgressMonitor)
	 */
public final String getPreviewContent(final TextEditBasedChangeGroup[] groups, final IRegion region, final boolean expand, final int surround, final IProgressMonitor monitor) throws CoreException {
    final Set cachedGroups = new HashSet(Arrays.asList(groups));
    final IDocument document = new Document(getCurrentDocument(monitor).get());
    // Marks the region in the document to be previewed
    final Position range = new Position(region.getOffset(), region.getLength());
    try {
        ComposableBufferChange change = null;
        final TextEditBasedChangeGroup[] changedGroups = getChangeGroups();
        LinkedList compositeUndo = new LinkedList();
        for (int index = 0; index < fChanges.size(); index++) {
            change = (ComposableBufferChange) fChanges.get(index);
            TextEdit copy = null;
            try {
                // Have to use a copy
                fCopier = new TextEditCopier(change.getEdit());
                copy = fCopier.perform();
                // Create a mapping from the copied edits to its originals
                final Map originalMap = new HashMap();
                for (final Iterator outer = change.getGroups().iterator(); outer.hasNext(); ) {
                    final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) outer.next();
                    for (final Iterator inner = group.getCachedEdits().iterator(); inner.hasNext(); ) {
                        final TextEdit originalEdit = (TextEdit) inner.next();
                        final TextEdit copiedEdit = fCopier.getCopy(originalEdit);
                        if (copiedEdit != null)
                            originalMap.put(copiedEdit, originalEdit);
                        else
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find a copy for the indexed text edit " + originalEdit.toString());
                    }
                }
                final ComposableBufferChangeGroup[] currentGroup = { null };
                final TextEdit[] currentEdit = { null };
                // Text edit processor which sets the change group and
                // current edit when processing
                final TextEditProcessor processor = new TextEditProcessor(document, copy, TextEdit.NONE) {

                    protected final boolean considerEdit(final TextEdit edit) {
                        final TextEdit originalEdit = (TextEdit) originalMap.get(edit);
                        if (originalEdit != null) {
                            currentEdit[0] = originalEdit;
                            boolean found = false;
                            for (int offset = 0; offset < changedGroups.length && !found; offset++) {
                                final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) changedGroups[offset];
                                if (group.containsEdit(originalEdit)) {
                                    currentGroup[0] = group;
                                    found = true;
                                }
                            }
                            if (!found)
                                currentGroup[0] = null;
                        } else if (!(edit instanceof MultiTextEdit)) {
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find the original of the copied text edit " + edit.toString());
                        }
                        return true;
                    }
                };
                final LinkedList eventUndos = new LinkedList();
                // Listener to record the undos on the document (offsets
                // relative to the document event)
                final IDocumentListener listener = new IDocumentListener() {

                    public final void documentAboutToBeChanged(final DocumentEvent event) {
                        final ComposableUndoEdit edit = new ComposableUndoEdit();
                        edit.setGroup(currentGroup[0]);
                        edit.setOriginal(currentEdit[0]);
                        edit.setUndo(createUndoEdit(document, event.getOffset(), event.getLength(), event.getText()));
                        eventUndos.addFirst(edit);
                    }

                    public final void documentChanged(final DocumentEvent event) {
                    // Do nothing
                    }
                };
                try {
                    // Record undos in LIFO order
                    document.addDocumentListener(listener);
                    processor.performEdits();
                } finally {
                    document.removeDocumentListener(listener);
                }
                compositeUndo.addFirst(eventUndos);
            } finally {
                fCopier = null;
            }
        }
        final IPositionUpdater positionUpdater = new IPositionUpdater() {

            public final void update(final DocumentEvent event) {
                final int eventOffset = event.getOffset();
                final int eventLength = event.getLength();
                final int eventOldEndOffset = eventOffset + eventLength;
                final String eventText = event.getText();
                final int eventNewLength = eventText == null ? 0 : eventText.length();
                final int eventNewEndOffset = eventOffset + eventNewLength;
                final int deltaLength = eventNewLength - eventLength;
                try {
                    final Position[] positions = event.getDocument().getPositions(COMPOSABLE_POSITION_CATEGORY);
                    for (int index = 0; index < positions.length; index++) {
                        final Position position = positions[index];
                        if (position.isDeleted())
                            continue;
                        final int offset = position.getOffset();
                        final int length = position.getLength();
                        final int end = offset + length;
                        if (offset > eventOldEndOffset) {
                            // position comes way after change - shift
                            position.setOffset(offset + deltaLength);
                        } else if (end < eventOffset) {
                        // position comes way before change - leave
                        // alone
                        } else if (offset == eventOffset) {
                        // leave alone, since the edits are overlapping
                        } else if (offset <= eventOffset && end >= eventOldEndOffset) {
                            // event completely internal to the position
                            // -
                            // adjust length
                            position.setLength(length + deltaLength);
                        } else if (offset < eventOffset) {
                            // event extends over end of position - include
                            // the
                            // replacement text into the position
                            position.setLength(eventNewEndOffset - offset);
                        } else if (end > eventOldEndOffset) {
                            // event extends from before position into it -
                            // adjust
                            // offset and length, including the replacement
                            // text into
                            // the position
                            position.setOffset(eventOffset);
                            int deleted = eventOldEndOffset - offset;
                            position.setLength(length - deleted + eventNewLength);
                        } else {
                            // event comprises the position - keep it at the
                            // same
                            // position, but always inside the replacement
                            // text
                            int newOffset = Math.min(offset, eventNewEndOffset);
                            int newEndOffset = Math.min(end, eventNewEndOffset);
                            position.setOffset(newOffset);
                            position.setLength(newEndOffset - newOffset);
                        }
                    }
                } catch (BadPositionCategoryException exception) {
                // ignore and return
                }
            }
        };
        try {
            document.addPositionCategory(COMPOSABLE_POSITION_CATEGORY);
            document.addPositionUpdater(positionUpdater);
            // Apply undos in LIFO order to get to the original document
            // Track the undos of edits which are in change groups to be
            // previewed and insert
            // Undo edits for them (corresponding to the linearized net
            // effect on the original document)
            final LinkedList undoQueue = new LinkedList();
            for (final Iterator outer = compositeUndo.iterator(); outer.hasNext(); ) {
                for (final Iterator inner = ((List) outer.next()).iterator(); inner.hasNext(); ) {
                    final ComposableUndoEdit edit = (ComposableUndoEdit) inner.next();
                    final ReplaceEdit undo = edit.getUndo();
                    final int offset = undo.getOffset();
                    final int length = undo.getLength();
                    final String text = undo.getText();
                    ComposableEditPosition position = new ComposableEditPosition();
                    if (cachedGroups.contains(edit.getGroup())) {
                        if (text == null || text.equals("")) {
                            //$NON-NLS-1$
                            position.offset = offset;
                            if (length != 0) {
                                // Undo is a delete, create final insert
                                // edit
                                position.length = 0;
                                position.setText(edit.getOriginalText());
                            } else
                                //$NON-NLS-1$
                                RefactoringCorePlugin.logErrorMessage("Dubious undo edit found: " + undo.toString());
                        } else if (length == 0) {
                            position.offset = offset;
                            // Undo is an insert, create final delete
                            // edit
                            //$NON-NLS-1$
                            position.setText("");
                            position.length = text.length();
                        } else {
                            // Undo is a replace, create final replace edit
                            position.offset = offset;
                            position.length = length;
                            position.setText(edit.getOriginalText());
                        }
                        document.addPosition(COMPOSABLE_POSITION_CATEGORY, position);
                    }
                    position = new ComposableEditPosition();
                    position.offset = undo.getOffset();
                    position.length = undo.getLength();
                    position.setText(undo.getText());
                    undoQueue.add(position);
                }
                for (final Iterator iterator = undoQueue.iterator(); iterator.hasNext(); ) {
                    final ComposableEditPosition position = (ComposableEditPosition) iterator.next();
                    document.replace(position.offset, position.length, position.getText());
                    iterator.remove();
                }
            }
            // Use a simple non deleting position updater for the range
            final IPositionUpdater markerUpdater = new NonDeletingPositionUpdater(MARKER_POSITION_CATEGORY);
            try {
                final Position[] positions = document.getPositions(COMPOSABLE_POSITION_CATEGORY);
                document.addPositionCategory(MARKER_POSITION_CATEGORY);
                document.addPositionUpdater(markerUpdater);
                document.addPosition(MARKER_POSITION_CATEGORY, range);
                for (int index = 0; index < positions.length; index++) {
                    final ComposableEditPosition position = (ComposableEditPosition) positions[index];
                    //$NON-NLS-1$
                    document.replace(position.offset, position.length, position.getText() != null ? position.getText() : "");
                }
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            } finally {
                document.removePositionUpdater(markerUpdater);
                try {
                    document.removePosition(MARKER_POSITION_CATEGORY, range);
                    document.removePositionCategory(MARKER_POSITION_CATEGORY);
                } catch (BadPositionCategoryException exception) {
                // Cannot happen
                }
            }
        } catch (BadPositionCategoryException exception) {
            RefactoringCorePlugin.log(exception);
        } finally {
            document.removePositionUpdater(positionUpdater);
            try {
                document.removePositionCategory(COMPOSABLE_POSITION_CATEGORY);
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            }
        }
        return getContent(document, new Region(range.offset, range.length), expand, surround);
    } catch (MalformedTreeException exception) {
        RefactoringCorePlugin.log(exception);
    } catch (BadLocationException exception) {
        RefactoringCorePlugin.log(exception);
    }
    return getPreviewDocument(monitor).get();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) TextEditCopier(org.eclipse.text.edits.TextEditCopier) NonDeletingPositionUpdater(org.eclipse.ltk.internal.core.refactoring.NonDeletingPositionUpdater) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) Position(org.eclipse.jface.text.Position) IDocumentListener(org.eclipse.jface.text.IDocumentListener) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) DocumentEvent(org.eclipse.jface.text.DocumentEvent) LinkedList(java.util.LinkedList) IPositionUpdater(org.eclipse.jface.text.IPositionUpdater) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IRegion(org.eclipse.jface.text.IRegion) Region(org.eclipse.jface.text.Region) Map(java.util.Map) HashMap(java.util.HashMap) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 5 with Region

use of org.eclipse.jface.text.Region in project che by eclipse.

the class FilledArgumentNamesMethodProposal method apply.

/*
     * @see ICompletionProposalExtension#apply(IDocument, char)
     */
@Override
public void apply(IDocument document, char trigger, int offset) {
    super.apply(document, trigger, offset);
    int baseOffset = getReplacementOffset();
    String replacement = getReplacementString();
    if (fArgumentOffsets != null && getTextViewer() != null) {
        LinkedModeModelImpl model = new LinkedModeModelImpl();
        for (int i = 0; i != fArgumentOffsets.length; i++) {
            LinkedPositionGroupImpl group = new LinkedPositionGroupImpl();
            RegionImpl region = new RegionImpl();
            region.setLength(fArgumentLengths[i]);
            region.setOffset(baseOffset + fArgumentOffsets[i]);
            group.addPositions(region);
            model.addGroups(group);
        }
        model.setEscapePosition(baseOffset + replacement.length());
        this.linkedModel = model;
        //                model.forceInstall();
        //                JavaEditor editor = getJavaEditor();
        //                if (editor != null) {
        //                    model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
        //                }
        //
        //                LinkedModeUI ui = new EditorLinkedModeUI(model, getTextViewer());
        //                ui.setExitPosition(getTextViewer(), baseOffset + replacement.length(), 0, Integer.MAX_VALUE);
        //                ui.setExitPolicy(new ExitPolicy(')', document));
        //                ui.setDoContextInfo(true);
        //                ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT);
        //                ui.enter();
        fSelectedRegion = new Region(baseOffset + replacement.length(), 0);
    } else {
        fSelectedRegion = new Region(baseOffset + replacement.length(), 0);
    }
}
Also used : LinkedPositionGroupImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedPositionGroupImpl) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) LinkedModeModelImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedModeModelImpl) RegionImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.RegionImpl) Point(org.eclipse.swt.graphics.Point)

Aggregations

Region (org.eclipse.jface.text.Region)396 IRegion (org.eclipse.jface.text.IRegion)304 Test (org.junit.Test)107 BadLocationException (org.eclipse.jface.text.BadLocationException)106 IHyperlink (org.eclipse.jface.text.hyperlink.IHyperlink)48 IDocument (org.eclipse.jface.text.IDocument)47 Point (org.eclipse.swt.graphics.Point)36 ITypedRegion (org.eclipse.jface.text.ITypedRegion)35 IndexedRegion (org.eclipse.wst.sse.core.internal.provisional.IndexedRegion)33 ITextSelection (org.eclipse.jface.text.ITextSelection)31 Position (org.eclipse.jface.text.Position)27 ArrayList (java.util.ArrayList)19 IFile (org.eclipse.core.resources.IFile)17 ITextViewerExtension5 (org.eclipse.jface.text.ITextViewerExtension5)17 ITextRegion (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion)17 IStructuredDocumentRegion (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion)15 StyledText (org.eclipse.swt.custom.StyledText)14 Node (org.w3c.dom.Node)14 ITextViewer (org.eclipse.jface.text.ITextViewer)13 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)13