Search in sources :

Example 36 with ITypedRegion

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

the class STPIndenter method findReferencePosition.

/**
 * Returns the reference position regarding to indentation for <code>position</code>,
 * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}. <code>fIndent</code> will contain
 * the relative indentation (in indentation units, not characters) after the call. If there is
 * a special alignment (e.g. for a method declaration where parameters should be aligned),
 * <code>fAlign</code> will contain the absolute position of the alignment reference
 * in <code>fDocument</code>, otherwise <code>fAlign</code> is set to
 * {@link STPHeuristicScanner#NOT_FOUND}.
 *
 * @param offset the offset for which the reference is computed
 * @param danglingElse whether a dangling else should be assumed at <code>position</code>
 * @param matchMode determines what kind of reference position should be returned.
 *     See {@link MatchMode}.
 * @return the reference statement relative to which <code>position</code>
 *         should be indented, or {@link STPHeuristicScanner#NOT_FOUND}
 */
public int findReferencePosition(int offset, boolean danglingElse, MatchMode matchMode) {
    // The indentation modification
    fIndent = 0;
    fExtraSpaces = 0;
    fAlign = NOT_FOUND;
    fPosition = offset;
    // declaration start instead of the opening brace.
    switch(matchMode) {
        case MATCH_BRACE:
            if (skipScope(STPSymbols.TokenLBRACE, STPSymbols.TokenRBRACE)) {
                try {
                    // Align with the opening brace that is on a line by its own
                    int lineOffset = fDocument.getLineOffset(fLine);
                    if (lineOffset <= fPosition && fDocument.get(lineOffset, fPosition - lineOffset).trim().isEmpty()) {
                        return fPosition;
                    }
                } catch (BadLocationException e) {
                // Concurrent modification - walk default path
                }
                // If the opening brace is not on the start of the line, skip to the start.
                int pos = skipToStatementStart(true, true);
                // indent is aligned with reference position
                fIndent = 0;
                return pos;
            } else {
                // If we can't find the matching brace, the heuristic is to unindent
                // by one against the normal position
                int pos = findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
                fIndent--;
                return pos;
            }
        case MATCH_PAREN:
            // Align parentheses.
            if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
                return fPosition;
            } else {
                // If we can't find the matching paren, the heuristic is to unindent by one
                // against the normal position.
                int pos = findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
                fIndent--;
                return pos;
            }
        case MATCH_CASE:
            // brace.
            return matchCaseAlignment();
        case MATCH_ACCESS_SPECIFIER:
            // opening brace.
            return matchAccessSpecifierAlignment();
        case MATCH_TYPE_DECLARATION:
            return matchTypeDeclaration();
        case REGULAR:
            break;
    }
    if (peekToken(offset) == STPSymbols.TokenCOLON) {
        int pos = fPosition;
        if (looksLikeTypeInheritanceDecl()) {
            fIndent = fPrefs.prefContinuationIndent;
            return fPosition;
        }
        fPosition = pos;
    }
    nextToken();
    // Skip access specifiers
    while (fToken == STPSymbols.TokenCOLON && isAccessSpecifier()) {
        nextToken();
    }
    int line = fLine;
    switch(fToken) {
        case STPSymbols.TokenGREATERTHAN:
        case STPSymbols.TokenRBRACE:
            // Skip the block and fall through.
            // If we can't complete the scope, reset the scan position
            int pos = fPosition;
            if (!skipScope())
                fPosition = pos;
            return skipToStatementStart(danglingElse, false);
        case STPSymbols.TokenSEMICOLON:
            // the token just after that is previous.start
            return skipToStatementStart(danglingElse, false);
        // Scope introduction: special treat who special is
        case STPSymbols.TokenLPAREN:
        case STPSymbols.TokenLBRACE:
        case STPSymbols.TokenLBRACKET:
            return handleScopeIntroduction(Math.min(offset + 1, fDocument.getLength()), true);
        case STPSymbols.TokenEOF:
            // trap when hitting start of document
            return NOT_FOUND;
        case STPSymbols.TokenEQUAL:
            // indent assignments, but don't do so if there is a String
            // after the assignment because SystemTap doesn't require
            // semi-colons to end lines and so this should be treated as
            // a complete assignment.
            pos = fPosition;
            while (pos < offset) {
                try {
                    ITypedRegion partition = ((IDocumentExtension3) fDocument).getPartition(STPPartitionScanner.STP_PARTITIONING, pos, danglingElse);
                    if (STPPartitionScanner.STP_STRING.equals(partition.getType()))
                        return skipToStatementStart(danglingElse, false);
                    pos = partition.getOffset() + partition.getLength();
                } catch (BadLocationException e) {
                    break;
                } catch (BadPartitioningException e) {
                    break;
                }
            }
            fIndent = fPrefs.prefAssignmentIndent;
            return fPosition;
        case STPSymbols.TokenCOLON:
            pos = fPosition;
            if (looksLikeCaseStatement()) {
                fIndent = fPrefs.prefCaseBlockIndent;
                return pos;
            }
            fPosition = pos;
            if (looksLikeTypeInheritanceDecl()) {
                fIndent = fPrefs.prefContinuationIndent;
                return pos;
            }
            fPosition = pos;
            if (looksLikeConstructorInitializer()) {
                fIndent = fPrefs.prefBlockIndent;
                return pos;
            }
            fPosition = pos;
            if (isConditional()) {
                fPosition = offset;
                fLine = line;
                return skipToPreviousListItemOrListStart();
            }
            fPosition = pos;
            return skipToPreviousListItemOrListStart();
        case STPSymbols.TokenQUESTIONMARK:
            if (fPrefs.prefTernaryDeepAlign) {
                setFirstElementAlignment(fPosition, offset + 1);
            } else {
                fIndent = fPrefs.prefTernaryIndent;
            }
            return fPosition;
        // Indentation for blockless introducers:
        case STPSymbols.TokenDO:
        case STPSymbols.TokenWHILE:
        case STPSymbols.TokenELSE:
            fIndent = fPrefs.prefSimpleIndent;
            return fPosition;
        case STPSymbols.TokenTRY:
            return skipToStatementStart(danglingElse, false);
        case STPSymbols.TokenRETURN:
        case STPSymbols.TokenTYPEDEF:
        case STPSymbols.TokenUSING:
            fIndent = fPrefs.prefContinuationIndent;
            return fPosition;
        case STPSymbols.TokenCONST:
            nextToken();
            if (fToken != STPSymbols.TokenRPAREN) {
                return skipToPreviousListItemOrListStart();
            }
        // $FALL-THROUGH$
        case STPSymbols.TokenRPAREN:
            if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
                int scope = fPosition;
                nextToken();
                if (fToken == STPSymbols.TokenIF || fToken == STPSymbols.TokenWHILE || fToken == STPSymbols.TokenFOR || fToken == STPSymbols.TokenFOREACH) {
                    fIndent = fPrefs.prefSimpleIndent;
                    return fPosition;
                }
                if (fToken == STPSymbols.TokenSWITCH) {
                    return fPosition;
                }
                fPosition = scope;
                if (looksLikeMethodDecl()) {
                    return skipToStatementStart(danglingElse, false);
                }
                if (fToken == STPSymbols.TokenCATCH) {
                    return skipToStatementStart(danglingElse, false);
                }
                fPosition = scope;
                if (looksLikeAnonymousTypeDecl()) {
                    return skipToStatementStart(danglingElse, false);
                }
            }
            // restore
            fPosition = offset;
            fLine = line;
            // else: fall through to default
            return skipToPreviousListItemOrListStart();
        case STPSymbols.TokenCOMMA:
            // indent by list-indent.
            return skipToPreviousListItemOrListStart();
        case STPSymbols.TokenPLUS:
        case STPSymbols.TokenMINUS:
        case STPSymbols.TokenLESSTHAN:
        case STPSymbols.TokenAGGREGATE:
        case STPSymbols.TokenSHIFTRIGHT:
        case STPSymbols.TokenSHIFTLEFT:
        case STPSymbols.TokenOTHER:
            // Math symbol, use skipToPreviousListItemOrListStart.
            return skipToPreviousListItemOrListStart();
        // Otherwise, fall-through
        default:
            // end in a semi-colon.  We want to indent to the same level as the statement.
            return skipToStatementStart(danglingElse, false);
    }
}
Also used : BadPartitioningException(org.eclipse.jface.text.BadPartitioningException) IDocumentExtension3(org.eclipse.jface.text.IDocumentExtension3) ITypedRegion(org.eclipse.jface.text.ITypedRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 37 with ITypedRegion

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

the class IndentUtil method indentLine.

/**
 * Indents a single line using the heuristic scanner. Multiline comments are
 * indented as specified by the <code>CCommentAutoIndentStrategy</code>.
 *
 * @param document the document
 * @param line the line to be indented
 * @param indenter the C indenter
 * @param scanner the heuristic scanner
 * @param commentLines the indent token comment booleans
 * @param lineIndex the zero-based line index
 * @param indentInsideLineComments option whether to indent inside line comments
 *             starting at column 0
 * @throws BadLocationException if the document got changed concurrently
 */
private static void indentLine(IDocument document, int line, STPIndenter indenter, STPHeuristicScanner scanner, boolean[] commentLines, int lineIndex, boolean indentInsideLineComments) throws BadLocationException {
    IRegion currentLine = document.getLineInformation(line);
    final int offset = currentLine.getOffset();
    // where we start searching for non-WS; after the "//" in single line comments
    int wsStart = offset;
    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_MULTILINE_COMMENT)) {
            indent = computeCommentIndent(document, line, scanner, startingPartition);
        } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
            indent = computePreprocessorIndent(document, line, startingPartition);
        } else if (!commentLines[lineIndex] && startingPartition.getOffset() == offset && startingPartition.getType().equals(STPPartitionScanner.STP_COMMENT)) {
            return;
        }
    }
    // standard C code indentation
    if (indent == null) {
        StringBuilder computed = indenter.computeIndentation(offset);
        if (computed != null)
            indent = computed.toString();
        else
            // $NON-NLS-1$
            indent = "";
    }
    // change document:
    // get current white space
    int lineLength = currentLine.getLength();
    int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
    if (end == STPHeuristicScanner.NOT_FOUND)
        end = offset + lineLength;
    int length = end - offset;
    String currentIndent = document.get(offset, length);
    // if 'indentInsideLineComments' is false, all comment lines are indented with the code
    if (length > 0 || !indentInsideLineComments) {
        ITypedRegion partition = TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, end, false);
        if (partition.getOffset() == end && STPPartitionScanner.STP_COMMENT.equals(partition.getType())) {
            commentLines[lineIndex] = true;
        }
    }
    // only change the document if it is a real change
    if (!indent.equals(currentIndent)) {
        document.replace(offset, length, indent);
    }
}
Also used : ITypedRegion(org.eclipse.jface.text.ITypedRegion) IRegion(org.eclipse.jface.text.IRegion)

Example 38 with ITypedRegion

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

the class GNUHyperlinkDetector method detectHyperlinks.

/**
 * Detector using RuleBasedScanner.
 */
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    if (documentLocation == null) {
        ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
        ITextFileBuffer buffer = bufferManager.getTextFileBuffer(textViewer.getDocument());
        if (buffer == null) {
            return null;
        }
        documentLocation = buffer.getLocation().removeLastSegments(1);
    }
    IDocument thisDoc = textViewer.getDocument();
    GNUHyperlinkScanner scanner = new GNUHyperlinkScanner();
    ITypedRegion partitionInfo = null;
    try {
        partitionInfo = thisDoc.getPartition(region.getOffset());
    } catch (org.eclipse.jface.text.BadLocationException e1) {
        e1.printStackTrace();
        return null;
    }
    scanner.setRange(thisDoc, partitionInfo.getOffset(), partitionInfo.getLength());
    Token tmpToken = (Token) scanner.nextToken();
    String tokenStr = (String) tmpToken.getData();
    if (tokenStr == null) {
        return null;
    }
    // null.
    while (region.getOffset() < scanner.getTokenOffset() || region.getOffset() > scanner.getOffset() || tokenStr.equals("_other")) {
        tmpToken = (Token) scanner.nextToken();
        tokenStr = (String) tmpToken.getData();
        if (tokenStr == null)
            return null;
    }
    Region tokenRegion = new Region(scanner.getTokenOffset(), scanner.getTokenLength());
    String line = "";
    try {
        line = thisDoc.get(tokenRegion.getOffset(), tokenRegion.getLength());
    } catch (org.eclipse.jface.text.BadLocationException e1) {
        e1.printStackTrace();
        return null;
    }
    // process file link
    if (tokenStr.equals(GNUHyperlinkScanner.FILE_NAME)) {
        Region pathRegion = null;
        int lineOffset = 0;
        // cut "* " if necessary
        if (line.startsWith("* ")) {
            lineOffset = 2;
            line = line.substring(2);
        }
        pathRegion = new Region(tokenRegion.getOffset() + lineOffset, line.length());
        if (documentLocation == null)
            return null;
        // Replace any escape characters added to name
        line = line.replaceAll("\\\\(.)", "$1");
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IFile fileLoc = (IFile) root.findMember(documentLocation.append(line));
        if (fileLoc != null && fileLoc.exists()) {
            return new IHyperlink[] { new FileHyperlink(pathRegion, fileLoc) };
        }
    }
    return null;
}
Also used : IFile(org.eclipse.core.resources.IFile) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Token(org.eclipse.jface.text.rules.Token) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ITypedRegion(org.eclipse.jface.text.ITypedRegion) Region(org.eclipse.jface.text.Region) ITypedRegion(org.eclipse.jface.text.ITypedRegion) IRegion(org.eclipse.jface.text.IRegion) IDocument(org.eclipse.jface.text.IDocument)

Example 39 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project erlide_eclipse by erlang.

the class ErlangHyperlinkDetector method detectHyperlinks.

private IHyperlink[] detectHyperlinks(final IDocument doc, final int offset) {
    final AbstractErlangEditor editor = getAdapter(AbstractErlangEditor.class);
    if (editor == null) {
        return null;
    }
    final ErlToken token = editor.getScanner().getTokenAt(offset);
    if (token == null) {
        return null;
    }
    final int tokenKind = token.getKind();
    if (tokenKind != ErlToken.KIND_ATOM && tokenKind != ErlToken.KIND_STRING && tokenKind != ErlToken.KIND_MACRO && tokenKind != ErlToken.KIND_VAR) {
        return null;
    }
    try {
        final ITypedRegion partition = doc.getPartition(offset);
        final ErlRegion region = new ErlRegion(token.getOffset(), token.getLength(), partition.getType());
        if (!IDocument.DEFAULT_CONTENT_TYPE.equals(region.getType())) {
            return null;
        }
        return new IHyperlink[] { new ErlangHyperlink(editor, region) };
    } catch (final BadLocationException e) {
        return null;
    }
}
Also used : IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) ITypedRegion(org.eclipse.jface.text.ITypedRegion) ErlToken(org.erlide.engine.services.parsing.ErlToken) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractErlangEditor(org.erlide.ui.editors.erl.AbstractErlangEditor)

Example 40 with ITypedRegion

use of org.eclipse.jface.text.ITypedRegion in project tmdm-studio-se by Talend.

the class ElementFKInfoAnnotaioner method buildAnnotations.

private Map<Annotation, Position> buildAnnotations(List<ITypedRegion> partitions) throws BadLocationException {
    Map<Annotation, Position> annotations = new HashMap<Annotation, Position>();
    // check if different partitions are connected by '+'
    int i = 0;
    for (; i < partitions.size(); i++) {
        ITypedRegion partion = partitions.get(i);
        String partionContent = document.get(partion.getOffset(), partion.getLength());
        if (partion.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) {
            if (i == 0 || i == partitions.size() - 1) {
                if (i == 0) {
                    if (partionContent.trim().startsWith(separator)) {
                        addToAnnotations(0, partionContent.length(), Messages.ElementFKInfoAnnotaioner_shouldNotAtStart, annotations);
                    }
                    if (i != partitions.size() - 1 && !partionContent.trim().endsWith(separator) && !partionContent.trim().isEmpty()) {
                        addToAnnotations(partion.getOffset(), partionContent.length(), Messages.ElementFKInfoAnnotaioner_missingAfter, annotations);
                    }
                }
                if (i == partitions.size() - 1) {
                    if (partionContent.trim().endsWith(separator)) {
                        addToAnnotations(partion.getOffset(), partionContent.length(), Messages.ElementFKInfoAnnotaioner_shouldNotAtEnd, annotations);
                    }
                    if (i != 0 && !partionContent.trim().startsWith(separator) && !partionContent.trim().isEmpty()) {
                        addToAnnotations(partion.getOffset(), partionContent.length(), Messages.ElementFKInfoAnnotaioner_missingBefore, annotations);
                    }
                }
            } else {
                if (!partionContent.trim().startsWith(separator)) {
                    addToAnnotations(partion.getOffset(), partionContent.length(), Messages.ElementFKInfoAnnotaioner_missingBefore, annotations);
                }
                if (!partionContent.trim().endsWith(separator)) {
                    addToAnnotations(partion.getOffset(), partionContent.length(), Messages.ElementFKInfoAnnotaioner_missingAfter, annotations);
                }
            }
        }
    }
    // check if partition is valid
    for (ITypedRegion partition : partitions) {
        if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
            int partionOffset = partition.getOffset();
            int partionLength = partition.getLength();
            String partion = document.get(partionOffset, partionLength);
            partionLength = partion.trim().length();
            int index = partion.indexOf(partion.trim());
            partionOffset += index;
            partion = partion.trim();
            if (partion.startsWith(separator)) {
                partion = partion.substring(1).trim();
                partionOffset++;
                partionLength--;
            }
            if (partion.endsWith(separator)) {
                partion = partion.substring(0, partion.length() - 1).trim();
                partionLength--;
            }
            if (partion.contains(separator)) {
                handleMergedXpaths(partion, partition, xPaths, annotations);
            } else {
                if (!xPaths.contains(partion) && !partion.isEmpty()) {
                    addToAnnotations(partionOffset, partionLength, Messages.bind(Messages.ElementFKInfoAnnotaioner_invalidXpath, partion), annotations);
                }
            }
        }
    }
    return annotations;
}
Also used : Position(org.eclipse.jface.text.Position) HashMap(java.util.HashMap) ITypedRegion(org.eclipse.jface.text.ITypedRegion) Annotation(org.eclipse.jface.text.source.Annotation)

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