Search in sources :

Example 91 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project linuxtools by eclipse.

the class ToggleCommentHandler method isSelectionCommented.

/**
 * Is the given selection on the specified document single-line commented?
 *
 * @param selection Selection to check
 * @param document The document
 * @return <code>true</code> iff all selected lines are commented
 */
public boolean isSelectionCommented(ISelection selection, IDocument document) {
    if (!(selection instanceof ITextSelection)) {
        return false;
    }
    ITextSelection textSelection = (ITextSelection) selection;
    if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) {
        return false;
    }
    try {
        IRegion block = getTextBlockFromSelection(textSelection, document);
        ITypedRegion[] regions = TextUtilities.computePartitioning(document, STPPartitionScanner.STP_PARTITIONING, block.getOffset(), block.getLength(), false);
        // [startline, endline,
        int[] lines = new int[regions.length * 2];
        // Count the number of lines that are selected.
        for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
            // Start line of region
            lines[j] = getFirstCompleteLineOfRegion(regions[i], document);
            // End line of region
            int length = regions[i].getLength();
            int offset = regions[i].getOffset() + length;
            if (length > 0) {
                offset--;
            }
            // If there is no startline for this region (startline = -1),
            // then there is no endline,
            // otherwise, get the line number of the endline and store it in
            // the array.
            lines[j + 1] = (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));
            assert i < regions.length;
            assert j < regions.length * 2;
        }
        // Perform the check
        boolean hasComment = false;
        for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
            // $NON-NLS-1$
            String prefix = "//";
            if (lines[j] >= 0 && lines[j + 1] >= 0) {
                if (isBlockCommented(lines[j], lines[j + 1], prefix, document)) {
                    hasComment = true;
                } else if (!isBlockEmpty(lines[j], lines[j + 1], document)) {
                    return false;
                }
            }
        }
        return hasComment;
    } catch (BadLocationException e) {
        ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
    }
    return false;
}
Also used : ITypedRegion(org.eclipse.jface.text.ITypedRegion) ITextSelection(org.eclipse.jface.text.ITextSelection) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 92 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project linuxtools by eclipse.

the class IndentUtil method computeIndent.

/**
 * Computes and returns the indentation for a source line.
 *
 * @param document the document
 * @param line the line in document
 * @param indenter the C indenter
 * @param scanner the scanner
 * @return the indent, never <code>null</code>
 * @throws BadLocationException
 */
public static String computeIndent(IDocument document, int line, STPIndenter indenter, STPHeuristicScanner scanner) throws BadLocationException {
    IRegion currentLine = document.getLineInformation(line);
    final int offset = currentLine.getOffset();
    String indent = null;
    if (offset < document.getLength()) {
        ITypedRegion partition = TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, true);
        ITypedRegion startingPartition = TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, false);
        String type = partition.getType();
        if (type.equals(STPPartitionScanner.STP_COMMENT)) {
            indent = computeCommentIndent(document, line, scanner, startingPartition);
        } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
            indent = computePreprocessorIndent(document, line, startingPartition);
        }
    }
    // standard C code indentation
    if (indent == null) {
        StringBuilder computed = indenter.computeIndentation(offset);
        if (computed != null) {
            indent = computed.toString();
        } else {
            // $NON-NLS-1$
            indent = "";
        }
    }
    return indent;
}
Also used : ITypedRegion(org.eclipse.jface.text.ITypedRegion) IRegion(org.eclipse.jface.text.IRegion)

Example 93 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project linuxtools by eclipse.

the class SpecfileChangelogFormatter method mergeChangelog.

@Override
public String mergeChangelog(String dateLine, String functionGuess, String defaultContent, IEditorPart changelog, String changeLogLocation, String fileLocation) {
    if (changelog instanceof SpecfileEditor) {
        SpecfileEditor specEditor = (SpecfileEditor) changelog;
        IDocument doc = specEditor.getDocumentProvider().getDocument(specEditor.getEditorInput());
        String[] positionCategories = doc.getPositionCategories();
        String contentTypesPositionCategory = null;
        // we need to find the one we want
        for (String positionCategory : positionCategories) {
            if (positionCategory.startsWith("__content_types_category")) {
                // $NON-NLS-1$
                contentTypesPositionCategory = positionCategory;
            }
        }
        if (contentTypesPositionCategory != null) {
            try {
                Position[] sectionPositions = doc.getPositions(contentTypesPositionCategory);
                ITypedRegion changelogPartition = null;
                for (Position position : sectionPositions) {
                    int offset = position.getOffset();
                    ITypedRegion partition = doc.getPartition(offset);
                    if (partition.getType().equals(SpecfilePartitionScanner.SPEC_CHANGELOG)) {
                        changelogPartition = partition;
                    }
                }
                // Temporary buffer for changelog text
                StringBuilder buf = new StringBuilder();
                String changelogText = EMPTY_STRING;
                String[] changelogLines = new String[] {};
                int offset = doc.getLength();
                int length = 0;
                // there was no changelog partition add it.
                if (changelogPartition == null) {
                    // make sure there are at least 2 newlines before
                    // the changelog section
                    String endString = doc.get(doc.getLength() - 2, 2);
                    if (endString.charAt(0) != '\n') {
                        buf.append('\n');
                    }
                    if (endString.charAt(1) != '\n') {
                        buf.append('\n');
                    }
                    // $NON-NLS-1$
                    buf.append("%changelog\n");
                // or get the old text and add the header
                } else {
                    offset = changelogPartition.getOffset();
                    length = changelogPartition.getLength();
                    changelogText = doc.get(offset, length);
                    // get old changelog text
                    // $NON-NLS-1$
                    changelogLines = changelogText.split("\n");
                    // add the %changelog header
                    buf.append(changelogLines[0]).append('\n');
                }
                // now add the entry stub
                buf.append(dateLine);
                buf.append('\n');
                // $NON-NLS-1$
                buf.append("- \n");
                // set the cursor at the end of the entry,
                // count back 2 '\n's
                int newCursorOffset = offset + buf.length() - 1;
                for (int i = 1; i < changelogLines.length; i++) {
                    buf.append('\n').append(changelogLines[i]);
                }
                // always terminate the file with a new line
                if (changelogLines.length > 0) {
                    buf.append('\n');
                }
                doc.replace(offset, length, buf.toString());
                specEditor.selectAndReveal(newCursorOffset, 0);
                specEditor.setFocus();
            } catch (BadPositionCategoryException | BadLocationException e) {
                SpecfileLog.logError(e);
            }
        }
    }
    return EMPTY_STRING;
}
Also used : Position(org.eclipse.jface.text.Position) SpecfileEditor(org.eclipse.linuxtools.internal.rpm.ui.editor.SpecfileEditor) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) ITypedRegion(org.eclipse.jface.text.ITypedRegion) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 94 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project xtext-eclipse by eclipse.

the class DocumentPartitionerTest method testSimple.

@Test
public void testSimple() throws Exception {
    XtextDocument document = getDocument("/* foo */ bar 345 grammar : so 'baz & so'");
    ITypedRegion partition = document.getPartition(0);
    assertEquals(0, partition.getOffset());
    assertEquals(9, partition.getLength());
    assertEquals(TerminalsTokenTypeToPartitionMapper.COMMENT_PARTITION, partition.getType());
    partition = document.getPartition(9);
    assertEquals(9, partition.getOffset());
    assertEquals(22, partition.getLength());
    assertEquals(IDocument.DEFAULT_CONTENT_TYPE, partition.getType());
    partition = document.getPartition(35);
    assertEquals(31, partition.getOffset());
    assertEquals(10, partition.getLength());
    assertEquals(TerminalsTokenTypeToPartitionMapper.STRING_LITERAL_PARTITION, partition.getType());
}
Also used : ITypedRegion(org.eclipse.jface.text.ITypedRegion) XtextDocument(org.eclipse.xtext.ui.editor.model.XtextDocument) Test(org.junit.Test)

Example 95 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project xtext-eclipse by eclipse.

the class DocumentPartitioner method computePartitioning.

/**
 * {@inheritDoc}
 * <p>
 * May be replaced or extended by subclasses.
 * </p>
 *
 * @since 2.2
 */
@Override
public synchronized ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) {
    checkInitialization();
    List<ITypedRegion> list = new ArrayList<ITypedRegion>();
    try {
        int endOffset = offset + length;
        Position[] category = getPositions();
        TypedPosition previous = null, current = null;
        int start, end, gapOffset;
        Position gap = new Position(0);
        int startIndex = getFirstIndexEndingAfterOffset(category, offset);
        int endIndex = getFirstIndexStartingAfterOffset(category, endOffset);
        for (int i = startIndex; i < endIndex; i++) {
            current = (TypedPosition) category[i];
            gapOffset = (previous != null) ? previous.getOffset() + previous.getLength() : 0;
            gap.setOffset(gapOffset);
            gap.setLength(current.getOffset() - gapOffset);
            if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) {
                start = Math.max(offset, gapOffset);
                end = Math.min(endOffset, gap.getOffset() + gap.getLength());
                list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE));
            }
            if (current.overlapsWith(offset, length)) {
                start = Math.max(offset, current.getOffset());
                end = Math.min(endOffset, current.getOffset() + current.getLength());
                list.add(new TypedRegion(start, end - start, current.getType()));
            }
            previous = current;
        }
        if (previous != null) {
            gapOffset = previous.getOffset() + previous.getLength();
            gap.setOffset(gapOffset);
            int gapLength = fDocument.getLength() - gapOffset;
            if (gapLength < 0) {
                clearPositionCache();
                return new TypedRegion[0];
            } else {
                gap.setLength(gapLength);
                if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) {
                    start = Math.max(offset, gapOffset);
                    end = Math.min(endOffset, fDocument.getLength());
                    list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE));
                }
            }
        }
        if (list.isEmpty())
            list.add(new TypedRegion(offset, length, IDocument.DEFAULT_CONTENT_TYPE));
    } catch (BadPositionCategoryException ex) {
        // Make sure we clear the cache
        clearPositionCache();
    } catch (RuntimeException ex) {
        // Make sure we clear the cache
        clearPositionCache();
        throw ex;
    }
    TypedRegion[] result = new TypedRegion[list.size()];
    list.toArray(result);
    return result;
}
Also used : Position(org.eclipse.jface.text.Position) TypedPosition(org.eclipse.jface.text.TypedPosition) TypedPosition(org.eclipse.jface.text.TypedPosition) ArrayList(java.util.ArrayList) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) ITypedRegion(org.eclipse.jface.text.ITypedRegion) ITypedRegion(org.eclipse.jface.text.ITypedRegion) TypedRegion(org.eclipse.jface.text.TypedRegion)

Aggregations

ITypedRegion (org.eclipse.jface.text.ITypedRegion)129 BadLocationException (org.eclipse.jface.text.BadLocationException)59 IRegion (org.eclipse.jface.text.IRegion)42 IDocument (org.eclipse.jface.text.IDocument)21 Region (org.eclipse.jface.text.Region)19 ArrayList (java.util.ArrayList)17 TypedRegion (org.eclipse.jface.text.TypedRegion)16 BadPositionCategoryException (org.eclipse.jface.text.BadPositionCategoryException)14 Position (org.eclipse.jface.text.Position)14 TypedPosition (org.eclipse.jface.text.TypedPosition)13 List (java.util.List)11 StyleRange (org.eclipse.swt.custom.StyleRange)7 Test (org.junit.Test)7 Iterator (java.util.Iterator)6 IStructuredModel (org.eclipse.wst.sse.core.internal.provisional.IStructuredModel)6 ITextSelection (org.eclipse.jface.text.ITextSelection)5 BadPartitioningException (org.eclipse.jface.text.BadPartitioningException)4 Document (org.eclipse.jface.text.Document)4 IDocumentExtension3 (org.eclipse.jface.text.IDocumentExtension3)4 IDocumentPartitioner (org.eclipse.jface.text.IDocumentPartitioner)4