Java Code Examples for org.netbeans.editor.Utilities#getRowFirstNonWhite()

The following examples show how to use org.netbeans.editor.Utilities#getRowFirstNonWhite() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void uncomment(BaseDocument doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
    final int lineCommentStringLen = lineCommentString.length();
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        // Get the first non-whitespace char on the current line
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);

        // If there is any, check wheter it's the line-comment-chars and remove them
        if (firstNonWhitePos != -1) {
            if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= lineCommentStringLen) {
                CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
                if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
                    doc.remove(firstNonWhitePos, lineCommentStringLen);
                }
            }
        }

        offset = Utilities.getRowStart(doc, offset, +1);
    }
}
 
Example 2
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void uncomment(BaseDocument doc, int startOffset, int lineCount) throws BadLocationException {
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        // Get the first non-whitespace char on the current line
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);

        // If there is any, check wheter it's the line-comment-chars and remove them
        if (firstNonWhitePos != -1) {
            if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= lineCommentStringLen) {
                CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
                if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
                    doc.remove(firstNonWhitePos, lineCommentStringLen);
                }
            }
        }

        offset = Utilities.getRowStart(doc, offset, +1);
    }
}
 
Example 3
Source File: JsFormatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Token<? extends JsTokenId> getFirstToken(IndentContext context, int offset) throws BadLocationException {
    BaseDocument doc = context.getDocument();
    int lineBegin = Utilities.getRowFirstNonWhite(doc, offset);

    if (lineBegin != -1) {
        if (context.isEmbedded()) {
            TokenSequence<? extends JsTokenId> ts = LexUtilities.getTokenSequence(
                    TokenHierarchy.get(doc), lineBegin, language);
            if (ts != null) {
                ts.moveNext();
                Token<? extends JsTokenId> token = ts.token();
                while (token != null && token.id() == JsTokenId.WHITESPACE) {
                    if (!ts.moveNext()) {
                        return null;
                    }
                    token = ts.token();
                }
                return token;
            }
        } else {
            return LexUtilities.getToken(doc, lineBegin, language);
        }
    }

    return null;
}
 
Example 4
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean allComments(BaseDocument doc, int startOffset, int lineCount) throws BadLocationException {
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
        if (firstNonWhitePos == -1) {
            return false;
        }
        
        if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos < lineCommentStringLen) {
            return false;
        }
        
        CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
        if (!CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
            return false;
        }
        
        offset = Utilities.getRowStart(doc, offset, +1);
    }
    return true;
}
 
Example 5
Source File: LexUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Return true iff the line for the given offset is a JavaScript comment line.
 * This will return false for lines that contain comments (even when the
 * offset is within the comment portion) but also contain code.
 */
public static boolean isCommentOnlyLine(BaseDocument doc, int offset)
    throws BadLocationException {
    int begin = Utilities.getRowFirstNonWhite(doc, offset);

    if (begin == -1) {
        return false; // whitespace only
    }

    Token<? extends PHPTokenId> token = LexUtilities.getToken(doc, begin);
    if (token != null) {
        return token.id() == PHPTokenId.PHP_LINE_COMMENT;
    }

    return false;
}
 
Example 6
Source File: CslTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static int getLineIndent(BaseDocument doc, int offset) {
    try {
        int start = Utilities.getRowStart(doc, offset);
        int end;

        if (Utilities.isRowWhite(doc, start)) {
            end = Utilities.getRowEnd(doc, offset);
        } else {
            end = Utilities.getRowFirstNonWhite(doc, start);
        }

        int indent = Utilities.getVisualColumn(doc, end);

        return indent;
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);

        return 0;
    }
}
 
Example 7
Source File: AbstractIndenter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Line generateBasicLine(int index) throws BadLocationException {
    Line line = new Line();
    line.index = index;
    line.offset = Utilities.getRowStartFromLineOffset(getDocument(), index);
    line.existingLineIndent = IndentUtils.lineIndent(getDocument(), line.offset);
    int nonWS = Utilities.getRowFirstNonWhite(getDocument(), line.offset);
    line.emptyLine = nonWS == -1;
    // if (first-non-whitespace-offset - line-start-offset) is different from 
    // existingLineIndent then line starts with tab characters which will need
    // to be replaced; if line is empty set tabIndentation to true just to make sure
    // possible tabs get replaced:
    line.tabIndentation = nonWS == -1 || line.existingLineIndent != (nonWS - line.offset);
    line.lineStartOffset = line.offset;
    line.lineEndOffset = Utilities.getRowEnd(getDocument(), line.offset);
    line.lineIndent = new ArrayList<IndentCommand>();
    line.lineIndent.add(new IndentCommand(IndentCommand.Type.NO_CHANGE, line.offset, getIndentationSize()));
    line.preliminaryNextLineIndent = new ArrayList<IndentCommand>();
    line.preliminaryNextLineIndent.add(new IndentCommand(IndentCommand.Type.NO_CHANGE, line.offset, getIndentationSize()));

    return line;
}
 
Example 8
Source File: AbstractIndenter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean doesLineStartWithOurLanguage(BaseDocument doc, int lineIndex, JoinedTokenSequence<T1> joinedTS) throws BadLocationException {
    int rowStartOffset = Utilities.getRowStartFromLineOffset(doc, lineIndex);
    int rowEndOffset = Utilities.getRowEnd(doc, rowStartOffset);
    int firstNonWhite = Utilities.getRowFirstNonWhite(doc, rowStartOffset);
    if (firstNonWhite != -1) {
        // there is something on the line:
        int newRowStartOffset = findLanguageOffset(joinedTS, rowStartOffset, rowEndOffset, true);
        if (newRowStartOffset == -1) {
            // but it is not our langauge
            return false;
        }
    }
    return true;
}
 
Example 9
Source File: ExtFormatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean hasTextBefore(JTextComponent target, String typedText) {
    BaseDocument doc = Utilities.getDocument(target);
    int dotPos = target.getCaret().getDot();
    try {
        int fnw = Utilities.getRowFirstNonWhite(doc, dotPos);
        return dotPos != fnw+typedText.length();
    } catch (BadLocationException e) {
        return false;
    }
}
 
Example 10
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Return true iff the line for the given offset is a comment line.
 * This will return false for lines that contain comments (even when the
 * offset is within the comment portion) but also contain code.
 */
public static boolean isCommentOnlyLine(BaseDocument doc, int offset)
    throws BadLocationException {
    int begin = Utilities.getRowFirstNonWhite(doc, offset);

    if (begin == -1) {
        return false; // whitespace only
    }

    if (begin == doc.getLength()) {
        return false;
    }

    return false; //doc.getText(begin, 2).equals("//") || doc.getText(begin, 1).equals("*");
}
 
Example 11
Source File: GroovyTypedTextInterceptor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void reindent(BaseDocument doc, int offset, TokenId id, Caret caret)
    throws BadLocationException {
    TokenSequence<GroovyTokenId> ts = LexUtilities.getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        ts.move(offset);

        if (!ts.moveNext() && !ts.movePrevious()) {
            return;
        }

        Token<GroovyTokenId> token = ts.token();

        if ((token.id() == id)) {
            final int rowFirstNonWhite = Utilities.getRowFirstNonWhite(doc, offset);
            // Ensure that this token is at the beginning of the line
            if (ts.offset() > rowFirstNonWhite) {
                return;
            }

            OffsetRange begin = OffsetRange.NONE;

            if (id == GroovyTokenId.RBRACE) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACE, GroovyTokenId.RBRACE);
            } else if (id == GroovyTokenId.RBRACKET) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACKET, GroovyTokenId.RBRACKET);
            }

            if (begin != OffsetRange.NONE) {
                int beginOffset = begin.getStart();
                int indent = GsfUtilities.getLineIndent(doc, beginOffset);
                previousAdjustmentIndent = GsfUtilities.getLineIndent(doc, offset);
                GsfUtilities.setLineIndentation(doc, offset, indent);
                previousAdjustmentOffset = caret.getDot();
            }
        }
    }
}
 
Example 12
Source File: LexUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static OffsetRange getCommentBlock(BaseDocument doc, int caretOffset) {
    // Check if the caret is within a comment, and if so insert a new
    // leaf "node" which contains the comment line and then comment block
    try {
        Token<GroovyTokenId> token = getToken(doc, caretOffset);

        if ((token != null) && (token.id() == GroovyTokenId.LINE_COMMENT)) {
            // First add a range for the current line
            int begin = Utilities.getRowStart(doc, caretOffset);
            int end = Utilities.getRowEnd(doc, caretOffset);

            if (LexUtilities.isCommentOnlyLine(doc, caretOffset)) {

                while (begin > 0) {
                    int newBegin = Utilities.getRowStart(doc, begin - 1);

                    if ((newBegin < 0) || !LexUtilities.isCommentOnlyLine(doc, newBegin)) {
                        begin = Utilities.getRowFirstNonWhite(doc, begin);
                        break;
                    }

                    begin = newBegin;
                }

                int length = doc.getLength();

                while (true) {
                    int newEnd = Utilities.getRowEnd(doc, end + 1);

                    if ((newEnd >= length) || !LexUtilities.isCommentOnlyLine(doc, newEnd)) {
                        end = Utilities.getRowLastNonWhite(doc, end) + 1;
                        break;
                    }

                    end = newEnd;
                }

                if (begin < end) {
                    return new OffsetRange(begin, end);
                }
            } else {
                // It's just a line comment next to some code
                TokenHierarchy<Document> th = TokenHierarchy.get((Document) doc);
                int offset = token.offset(th);
                return new OffsetRange(offset, offset + token.length());
            }
        }
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
    }

    return OffsetRange.NONE;
}
 
Example 13
Source File: GroovyFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void computeIndents(BaseDocument doc, int initialIndent, int startOffset, int endOffset, ParserResult info,
        List<Integer> offsets,
        List<Integer> indents,
        boolean indentEmptyLines, boolean includeEnd, boolean indentOnly
    ) {
    // PENDING:
    // The reformatting APIs in NetBeans should be lexer based. They are still
    // based on the old TokenID apis. Once we get a lexer version, convert this over.
    // I just need -something- in place until that is provided.

    try {
        // Algorithm:
        // Iterate over the range.
        // Accumulate a token balance ( {,(,[, and keywords like class, case, etc. increases the balance,
        //      },),] and "end" decreases it
        // If the line starts with an end marker, indent the line to the level AFTER the token
        // else indent the line to the level BEFORE the token (the level being the balance * indentationSize)
        // Compute the initial balance and indentation level and use that as a "base".
        // If the previous line is not "done" (ends with a comma or a binary operator like "+" etc.
        // add a "hanging indent" modifier.
        // At the end of the day, we're recording a set of line offsets and indents.
        // This can be used either to reformat the buffer, or indent a new line.

        // State:
        int offset = Utilities.getRowStart(doc, startOffset); // The line's offset
        int end = endOffset;

        int indentSize = IndentUtils.indentLevelSize(doc);
        int hangingIndentSize = hangingIndentSize();

        // Pending - apply comment formatting too?


        // Build up a set of offsets and indents for lines where I know I need
        // to adjust the offset. I will then go back over the document and adjust
        // lines that are different from the intended indent. By doing piecemeal
        // replacements in the document rather than replacing the whole thing,
        // a lot of things will work better: breakpoints and other line annotations
        // will be left in place, semantic coloring info will not be temporarily
        // damaged, and the caret will stay roughly where it belongs.

        // The token balance at the offset
        int balance = 0;
        // The bracket balance at the offset ( parens, bracket, brace )
        int bracketBalance = 0;
        boolean continued = false;

        while ((!includeEnd && offset < end) || (includeEnd && offset <= end)) {
            int indent; // The indentation to be used for the current line
            int hangingIndent = continued ? (hangingIndentSize) : 0;

            if (isInLiteral(doc, offset)) {
                // Skip this line - leave formatting as it is prior to reformatting
                indent = GsfUtilities.getLineIndent(doc, offset);

            } else if (isEndIndent(doc, offset)) {
                indent = (balance - 1) * indentSize + hangingIndent + initialIndent;
            } else {
                indent = balance * indentSize + hangingIndent + initialIndent;
            }

            int endOfLine = Utilities.getRowEnd(doc, offset) + 1;

            if (isJavaDocComment(doc, offset, endOfLine)) {
                indent++;
            }

            if (indent < 0) {
                indent = 0;
            }

            int lineBegin = Utilities.getRowFirstNonWhite(doc, offset);

            // Insert whitespace on empty lines too -- needed for abbreviations expansion
            if (lineBegin != -1 || indentEmptyLines) {
                // Don't do a hanging indent if we're already indenting beyond the parent level?

                indents.add(Integer.valueOf(indent));
                offsets.add(Integer.valueOf(offset));
            }



            if (lineBegin != -1) {
                balance += getTokenBalance(doc, lineBegin, endOfLine, true);
                bracketBalance += getTokenBalance(doc, lineBegin, endOfLine, false);
                continued = isLineContinued(doc, offset, bracketBalance);
            }

            offset = endOfLine;
        }
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
    }
}
 
Example 14
Source File: WhereUsedElement.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static WhereUsedElement create(FileObject fileObject, Entry entry, ElementKind kind, boolean related) {
    Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList());
    String name = entry.getName();
    OffsetRange range = entry.getDocumentRange();

    int start = range.getStart();
    int end = range.getEnd();
    
    int sta = start;
    int en = start; // ! Same line as start
    String content = null;
    
    BaseDocument bdoc = GsfUtilities.getDocument(fileObject, true);
    try {
        bdoc.readLock();

        // I should be able to just call tree.getInfo().getText() to get cached
        // copy - but since I'm playing fast and loose with compilationinfos
        // for for example find subclasses (using a singly dummy FileInfo) I need
        // to read it here instead
        content = bdoc.getText(0, bdoc.getLength());
        sta = Utilities.getRowFirstNonWhite(bdoc, start);

        if (sta == -1) {
            sta = Utilities.getRowStart(bdoc, start);
        }

        en = Utilities.getRowLastNonWhite(bdoc, start);

        if (en == -1) {
            en = Utilities.getRowEnd(bdoc, start);
        } else {
            // Last nonwhite - left side of the last char, not inclusive
            en++;
        }

        // Sometimes the node we get from the AST is for the whole block
        // (e.g. such as the whole class), not the argument node. This happens
        // for example in Find Subclasses out of the index. In this case
        if (end > en) {
            end = start + name.length();

            if (end > bdoc.getLength()) {
                end = bdoc.getLength();
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        bdoc.readUnlock();
    }

    StringBuilder sb = new StringBuilder();
    if (end < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        sta = end;
    }
    if (start < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        start = sta;
    }
    if (en < end) {
        // XXX Shouldn't happen, but I still have AST offset errors
        en = end;
    }
    sb.append(encodeCharRefs(content.subSequence(sta, start).toString()));
    sb.append("<b>"); // NOI18N
    sb.append(content.subSequence(start, end));
    sb.append("</b>"); // NOI18N
    sb.append(encodeCharRefs(content.subSequence(end, en).toString()));
    if(!related) {
        sb.append(NbBundle.getMessage(WhereUsedElement.class, "MSG_Unrelated_Where_Used_Occurance")); //NOI18N
    }


    CloneableEditorSupport ces = GsfUtilities.findCloneableEditorSupport(fileObject);
    PositionRef ref1 = ces.createPositionRef(start, Bias.Forward);
    PositionRef ref2 = ces.createPositionRef(end, Bias.Forward);
    PositionBounds bounds = new PositionBounds(ref1, ref2);

    return new WhereUsedElement(bounds, sb.toString().trim(), 
            fileObject, name, new OffsetRange(start, end), icon);
}
 
Example 15
Source File: PhpTypedBreakInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Determine if an "end" or "}" is missing following the caret offset. The
 * logic used is to check the text on the current line for block initiators
 * (e.g. "def", "for", "{" etc.) and then see if a corresponding close is
 * found after the same indentation level.
 *
 * @param doc The document to be checked
 * @param offset The offset of the current line
 * @param skipJunk If false, only consider the current line (of the offset)
 * as the possible "block opener"; if true, look backwards across empty
 * lines and comment lines as well.
 * @param insertEndResult Null, or a boolean 1-element array whose first
 * element will be set to true iff this method determines that "end" should
 * be inserted
 * @param insertRBraceResult Null, or a boolean 1-element array whose first
 * element will be set to true iff this method determines that "}" should be
 * inserted
 * @param startOffsetResult Null, or an integer 1-element array whose first
 * element will be set to the starting offset of the opening block.
 * @param indentResult Null, or an integer 1-element array whose first
 * element will be set to the indentation level "end" or "}" should be
 * indented to when inserted.
 * @return true if something is missing; insertEndResult, insertRBraceResult
 * and identResult will provide the more specific return values in their
 * first elements.
 */
static boolean isEndMissing(BaseDocument doc, int offset, boolean skipJunk,
        boolean[] insertEndResult, boolean[] insertRBraceResult, int[] startOffsetResult,
        int[] indentResult, PHPTokenId insertingEnd) throws BadLocationException {
    if (startOffsetResult != null) {
        startOffsetResult[0] = Utilities.getRowFirstNonWhite(doc, offset);
    }
    TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, offset);
    if (ts == null) {
        return false;
    }
    ts.move(offset);
    if (!ts.moveNext() && !ts.movePrevious()) {
        return false;
    }
    Token<? extends PHPTokenId> token = ts.token();
    int balance = 1;
    boolean endOfFile = false;
    if (insertingEnd == PHPTokenId.PHP_CURLY_CLOSE) {
        while ((token.id() == PHPTokenId.PHP_CURLY_OPEN
                || token.id() == PHPTokenId.PHP_CURLY_CLOSE
                || token.id() == PHPTokenId.WHITESPACE)
                && !endOfFile) {
            if (token.id() == PHPTokenId.PHP_CURLY_OPEN) {
                balance++;
            } else if (token.id() == PHPTokenId.PHP_CURLY_CLOSE) {
                balance--;
            }
            if (ts.moveNext()) {
                token = ts.token();
            } else {
                endOfFile = true;
            }
        }
        if (endOfFile) {
            if (balance == 1) {
                return true;
            }
        }
    }
    return false;
}
 
Example 16
Source File: PhpTypedTextInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void reindent(BaseDocument doc, int offset, TokenId id, Caret caret) throws BadLocationException {
    TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, offset);
    if (ts != null) {
        ts.move(offset);
        if (!ts.moveNext() && !ts.movePrevious()) {
            return;
        }
        Token<? extends PHPTokenId> token = ts.token();
        if ((token.id() == id)) {
            final int rowFirstNonWhite = Utilities.getRowFirstNonWhite(doc, offset);
            if (id == PHPTokenId.PHP_CURLY_OPEN && ts.offset() == rowFirstNonWhite
                    && ts.movePrevious()) {
                // The curly is at the first nonwhite char at the line.
                // Do we need to indent the { according previous line?
                int previousExprestion = LexUtilities.findStartTokenOfExpression(ts);
                int previousIndent = Utilities.getRowIndent(doc, previousExprestion);
                int currentIndent = Utilities.getRowIndent(doc, offset);
                int newIndent = IndentUtils.countIndent(doc, offset, previousIndent);
                if (newIndent != currentIndent) {
                    GsfUtilities.setLineIndentation(doc, offset, Math.max(newIndent, 0));
                }
            } else if (id == PHPTokenId.WHITESPACE || (id == PHPTokenId.PHP_TOKEN && token.text().charAt(0) == ':')) { // ":" handles "default:"
                if (id == PHPTokenId.WHITESPACE) {
                    LexUtilities.findPreviousToken(ts, Arrays.asList(PHPTokenId.PHP_CASE));
                } else {
                    LexUtilities.findPreviousToken(ts, Arrays.asList(PHPTokenId.PHP_DEFAULT));
                }
                if (ts.offset() >= rowFirstNonWhite) { //previous "case" or "default" on one line with typed char
                    LexUtilities.findPreviousToken(ts, Arrays.asList(PHPTokenId.PHP_SWITCH));
                    Token<? extends PHPTokenId> firstCaseInSwitch = LexUtilities.findNextToken(ts, Arrays.asList(PHPTokenId.PHP_CASE));
                    if (firstCaseInSwitch != null && firstCaseInSwitch.id() == PHPTokenId.PHP_CASE) {
                        int indentOfFirstCase = GsfUtilities.getLineIndent(doc, ts.offset());
                        GsfUtilities.setLineIndentation(doc, offset, indentOfFirstCase);
                    }
                }
            } else if (id == PHPTokenId.PHP_CURLY_CLOSE) {
                OffsetRange begin = LexUtilities.findBwd(doc, ts, PHPTokenId.PHP_CURLY_OPEN, '{', PHPTokenId.PHP_CURLY_CLOSE, '}');
                if (begin != OffsetRange.NONE) {
                    int beginOffset = begin.getStart();
                    int indent = GsfUtilities.getLineIndent(doc, beginOffset);
                    previousAdjustmentIndent = GsfUtilities.getLineIndent(doc, offset);
                    GsfUtilities.setLineIndentation(doc, offset, indent);
                    previousAdjustmentOffset = caret.getDot();
                }
            }
        }
    }
}
 
Example 17
Source File: CoverageHighlightsContainer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Highlights(long version, int startOffset, int endOffset, FileCoverageDetails details) {
    this.version = version;
    this.startOffsetBoundary = startOffset;
    this.endOffsetBoundary = endOffset;

    if (lastPositions == null) {
        positions = new ArrayList<Position>();
        types = new ArrayList<CoverageType>();
        for (int lineno = 0, maxLines = details.getLineCount(); lineno < maxLines; lineno++) {
            CoverageType type = details.getType(lineno);
            if (type == CoverageType.COVERED || type == CoverageType.INFERRED ||
                    type == CoverageType.NOT_COVERED || type == CoverageType.PARTIAL) {
                try {
                    int offset = Utilities.getRowStartFromLineOffset(doc, lineno);
                    if (offset == -1) {
                        continue;
                    }
                    // Attach the highlight position to the beginning of text, such
                    // that if we insert a new line at the beginning of a line (or in
                    // the whitespace region) the highlight will move down with the
                    // text
                    int rowStart = Utilities.getRowFirstNonWhite(doc, offset);
                    if (rowStart != -1) {
                        offset = rowStart;
                    }
                    Position pos = doc.createPosition(offset, Position.Bias.Forward);
                    positions.add(pos);
                    types.add(type);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        lastPositions = positions;
        lastTypes = types;
    } else {
        positions = lastPositions;
        types = lastTypes;
    }

    try {
        int lineStart = Utilities.getRowFirstNonWhite(doc, startOffsetBoundary);
        if (lineStart == -1) {
            lineStart = Utilities.getRowStart(doc, startOffsetBoundary);
            index = findPositionIndex(positions, lineStart);
            if (index < 0) {
                index = -index;
            }
        }
    } catch (BadLocationException ble) {
    }
}
 
Example 18
Source File: JsTypedTextInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void reindent(BaseDocument doc, int offset, TokenId id, Caret caret)
        throws BadLocationException {
        TokenSequence<? extends JsTokenId> ts = LexUtilities.getTokenSequence(
                doc, offset, language);

        if (ts != null) {
            ts.move(offset);

            if (!ts.moveNext() && !ts.movePrevious()) {
                return;
            }

            Token<? extends JsTokenId> token = ts.token();

            if ((token.id() == id)) {
                final int rowFirstNonWhite = Utilities.getRowFirstNonWhite(doc, offset);
                // Ensure that this token is at the beginning of the line
                if (ts.offset() > rowFirstNonWhite) {
//                    if (RubyUtils.isRhtmlDocument(doc)) {
//                        // Allow "<%[whitespace]*" to preceed
//                        String s = doc.getText(rowFirstNonWhite, ts.offset()-rowFirstNonWhite);
//                        if (!s.matches("<%\\s*")) {
//                            return;
//                        }
//                    } else {
                        return;
//                    }
                }

                OffsetRange begin = OffsetRange.NONE;

                if (id == JsTokenId.BRACKET_RIGHT_CURLY) {
                    begin = LexUtilities.findBwd(doc, ts, JsTokenId.BRACKET_LEFT_CURLY, JsTokenId.BRACKET_RIGHT_CURLY);
                } else if (id == JsTokenId.BRACKET_RIGHT_BRACKET) {
                    begin = LexUtilities.findBwd(doc, ts, JsTokenId.BRACKET_LEFT_BRACKET, JsTokenId.BRACKET_RIGHT_BRACKET);
                }

                if (begin != OffsetRange.NONE) {
                    int beginOffset = begin.getStart();
                    int indent = GsfUtilities.getLineIndent(doc, beginOffset);
                    previousAdjustmentIndent = GsfUtilities.getLineIndent(doc, offset);
                    GsfUtilities.setLineIndentation(doc, offset, indent);
                    previousAdjustmentOffset = caret.getDot();
                }
            }
        }
    }
 
Example 19
Source File: JsFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int isEndIndent(IndentContext context, int offset) throws BadLocationException {
    BaseDocument doc = context.getDocument();
    int lineBegin = Utilities.getRowFirstNonWhite(doc, offset);

    if (lineBegin != -1) {
        Token<?extends JsTokenId> token = getFirstToken(context, offset);

        if (token == null) {
            return 0;
        }

        TokenId id = token.id();

        // If the line starts with an end-marker, such as "end", "}", "]", etc.,
        // find the corresponding opening marker, and indent the line to the same
        // offset as the beginning of that line.
        if (id == JsTokenId.BRACKET_RIGHT_CURLY || id == JsTokenId.BRACKET_RIGHT_BRACKET
                /*|| id == JsTokenId.BRACKET_RIGHT_PAREN*/) {
            int indents = 1;

            // Check if there are multiple end markers here... if so increase indent level.
            // This should really do an iteration... for now just handling the most common
            // scenario in JavaScript where we have }) in object literals
            int lineEnd = Utilities.getRowEnd(doc, offset);
            int newOffset = offset;
            while (newOffset < lineEnd && token != null) {
                newOffset = newOffset + token.length();
                if (newOffset < doc.getLength()) {
                    token = LexUtilities.getToken(doc, newOffset, language);
                    if (token != null) {
                        id = token.id();
                        if (id == JsTokenId.WHITESPACE) {
                            continue;
                        } else {
                            break;
                        }
                    }
                }
            }

            return indents;
        }
    }

    return 0;
}
 
Example 20
Source File: OverrideEditorActions.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        BaseDocument doc = (BaseDocument)target.getDocument();
        try {
            int dot = caret.getDot();
            // #232675: if bounds are defined, use them rather than line start/end
            Object o = target.getClientProperty(PROP_NAVIGATE_BOUNDARIES);
            PositionRegion bounds = null;
            int lineStartPos = Utilities.getRowStart(target, dot);
            
            if (o instanceof PositionRegion) {
                bounds = (PositionRegion)o;
                int start = bounds.getStartOffset();
                int end = bounds.getEndOffset();
                int boundLineStart = Utilities.getRowStart(target, start);
                // refinement: only use the boundaries if the caret is at the same line
                // as boundary start; otherwise ignore the boundary and use document lines.
                if (boundLineStart == lineStartPos && dot > start && dot <= end) {
                    // move to the region start
                    dot = start;
                } else {
                    bounds = null;
                }
            }
            
            if (bounds == null) {
                if (homeKeyColumnOne) { // to first column
                    dot = lineStartPos;
                } else { // either to line start or text start
                    int textStartPos = Utilities.getRowFirstNonWhite(doc, lineStartPos);
                    if (textStartPos < 0) { // no text on the line
                        textStartPos = Utilities.getRowEnd(target, lineStartPos);
                    }
                    if (dot == lineStartPos) { // go to the text start pos
                        dot = textStartPos;
                    } else if (dot <= textStartPos) {
                        dot = lineStartPos;
                    } else {
                        dot = textStartPos;
                    }
                }
            }
            // For partial view hierarchy check bounds
            dot = Math.max(dot, target.getUI().getRootView(target).getStartOffset());
            String actionName = (String) getValue(Action.NAME);
            boolean select = selectionBeginLineAction.equals(actionName)
                    || selectionLineFirstColumnAction.equals(actionName);
            
            // If possible scroll the view to its begining horizontally
            // to ease user's orientation in the code.
            Rectangle r = target.modelToView(dot);
            Rectangle visRect = target.getVisibleRect();
            if (r.getMaxX() < visRect.getWidth()) {
                r.x = 0;
                target.scrollRectToVisible(r);
            }
            target.putClientProperty("navigational.action", SwingConstants.WEST);
            if (select) {
                caret.moveDot(dot);
            } else {
                caret.setDot(dot);
            }
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}