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

The following examples show how to use org.netbeans.editor.Utilities#getRowStart() . 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 static int[] getPositions(TokenSequence<TplTopTokenId> ts, boolean commentIt, int caretOffset,
        JTextComponent target, TplMetaData tplMetaData) throws BadLocationException {
    int[] positions = new int[2];
    if (commentIt) {
        if (Utilities.isSelectionShowing(target)) {
            positions[0] = caretOffset;
            positions[1] = target.getSelectionEnd();
        } else {
            positions[0] = Utilities.getRowStart((BaseDocument) target.getDocument(), caretOffset);
            positions[1] = Utilities.getRowEnd((BaseDocument) target.getDocument(), caretOffset);
        }
    } else {
        while (ts.movePrevious() && ts.token().id() != TplTopTokenId.T_SMARTY_OPEN_DELIMITER) {
            //NOOP - just find start
        }
        positions[0] = ts.offset();
        while (ts.moveNext() && ts.token().id() != TplTopTokenId.T_SMARTY_CLOSE_DELIMITER) {
            //NOOP - just find end
        }
        positions[1] = ts.offset() - tplMetaData.getCloseDelimiter().length() - 2;
    }
    return positions;
}
 
Example 2
Source File: IndentCasesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void test(String fileName, int lineNum, int offset, int endLineNum, int endOffset) throws Exception {
    EditorOperator.closeDiscardAll();
    EditorOperator op = openFile(fileName);
    op.setCaretPositionToLine(lineNum);
    op.setCaretPositionRelative(offset - 1);
    if (debug) {
        Thread.sleep(3000); // to be visible ;-)
    }
    op.pressKey(KeyEvent.VK_ENTER);
    op.waitModified(true);
    int newPossition = op.txtEditorPane().getCaretPosition();
    int newLine = Utilities.getLineOffset(doc, newPossition) + 1;
    int newOffset = newPossition - Utilities.getRowStart(doc, newPossition);
    if (debug) {
        Thread.sleep(3000); // to be visible ;-)
    }
    assertEquals("FINAL POSSITION", endLineNum, newLine);
    assertEquals("FINAL POSSITION", endOffset - 1, newOffset);
}
 
Example 3
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 4
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 5
Source File: TagBasedFormatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected int getIndentForTagParameter(BaseDocument doc, TokenItem tag) throws BadLocationException{
    int tagStartLine = Utilities.getLineOffset(doc, tag.getOffset());
    TokenItem currentToken = tag.getNext();
    
    /*
     * Find the offset of the first attribute if it is specified on the same line as the opening of the tag
     * e.g. <tag   |attr=
     * 
     */
    while (currentToken != null && isWSTag(currentToken) && tagStartLine == Utilities.getLineOffset(doc, currentToken.getOffset())){
        currentToken = currentToken.getNext();
    }
    
    if (tag != null && !isWSTag(currentToken) && tagStartLine == Utilities.getLineOffset(doc, currentToken.getOffset())){
        return currentToken.getOffset() - Utilities.getRowIndent(doc, currentToken.getOffset()) - Utilities.getRowStart(doc, currentToken.getOffset());
    }
    
    return getShiftWidth(); // default;
}
 
Example 6
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean allComments(BaseDocument doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
    final int lineCommentStringLen = lineCommentString.length();
    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 7
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
private static int getColumn (final int pos, final JTextComponent editor) {
  try {
    return pos - Utilities.getRowStart(editor, pos) + 1;
  }
  catch (BadLocationException e) {
    LOGGER.error("Bad location", e);
  }
  return -1;
}
 
Example 8
Source File: JspIndenter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected int getPreservedLineInitialIndentation(JoinedTokenSequence<JspTokenId> ts)
        throws BadLocationException {
    int[] index = ts.index();
    boolean found = false;
    do {
        if (ts.token().id() == JspTokenId.COMMENT) {
            String comment = ts.token().text().toString().trim();
            if (comment.startsWith("<%--")) {
                found = true;
                break;
            }
        } else {
            break;
        }
    } while (ts.movePrevious());
    int indent = 0;
    if (found) {
        int lineStart = Utilities.getRowStart(getDocument(), ts.offset());
        // TODO: can comment token start with spaces?? if yes then adjust
        // column to point to first non-whitespace
        int column = ts.offset();
        indent = column - lineStart;
    }
    ts.moveIndex(index);
    ts.moveNext();
    return indent;
}
 
Example 9
Source File: AbstractTokenList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void setStartOffset(int offset) {
    currentWord = null;
    currentStartOffset = (-1);
    this.ignoreBefore = offset;
    try {
        this.nextSearchOffset = Utilities.getRowStart(doc, offset);
    } catch (BadLocationException ex) {
        Logger.getLogger(AbstractTokenList.class.getName()).log(Level.FINE, null, ex);
        this.nextSearchOffset = offset;
    }
}
 
Example 10
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void comment(BaseDocument baseDocument) throws BadLocationException {
    int offsetCommentStart;
    int offsetCommentEnd;
    if (isSelection) {
        offsetCommentStart = getStart();
        offsetCommentEnd = getEnd();
    } else {
        offsetCommentStart = Utilities.getRowStart(baseDocument, getStart());
        offsetCommentEnd = Utilities.getRowEnd(baseDocument, getEnd());
    }
    baseDocument.insertString(offsetCommentStart, TwigTopLexer.OPEN_COMMENT, null);
    baseDocument.insertString(offsetCommentEnd + TwigTopLexer.OPEN_COMMENT.length(), TwigTopLexer.CLOSE_COMMENT, null);
}
 
Example 11
Source File: ExtFinderFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public int adjustStartPos(BaseDocument doc, int startPos) {
    origStartPos = startPos;
    try {
        return Utilities.getRowStart(doc, startPos);
    } catch (BadLocationException e) {
        return startPos;
    }
}
 
Example 12
Source File: HintsTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<ErrorDescription> getErrorDescriptionsAt(CompilationInfo info, Context context, Document doc) throws BadLocationException {
    int rowStart = Utilities.getRowStart((BaseDocument) doc, context.getPosition());
    int rowEnd = Utilities.getRowEnd((BaseDocument) doc, context.getPosition());

    return new HintsInvoker(HintsSettings.getSettingsFor(info.getFileObject()), rowStart, rowEnd, context.getCancel()).computeHints(info);
}
 
Example 13
Source File: ExtFinderFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public int adjustStartPos(BaseDocument doc, int startPos) {
    origStartPos = startPos;
    try {
        return Utilities.getRowStart(doc, startPos);
    } catch (BadLocationException e) {
        return startPos;
    }
}
 
Example 14
Source File: AbstractIndenter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int findPreviousOccuranceOfOurLanguage(JoinedTokenSequence<T1> ts, int start) throws BadLocationException {
    // this method finds previous non-empty line and
    // will try to find our language there:

    // find line start and move to previous line if possible:
    int lineStart = Utilities.getRowStart(getDocument(), start);
    if (lineStart > 0) {
        lineStart--;
    }
    // find first non-whitespace character going backwards:
    int offset = Utilities.getFirstNonWhiteRow(getDocument(), start, false);
    if (offset == -1) {
        offset = 0;
    }
    // find beginning of this line
    lineStart = Utilities.getRowStart(getDocument(), offset);

    // use line start as beginning for our language search:
    if (ts.move(lineStart, true)) {
        if (!ts.moveNext()) {
            ts.movePrevious();
        }
        offset = ts.offset();
        if (offset > start) {
            return -1;
        } else {
            return offset;
        }
    }
    return -1;
}
 
Example 15
Source File: AbstractTokenList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void setStartOffset (int offset) {
    currentWord = null;
    currentStartOffset = (-1);
    this.ignoreBefore = offset;
    try {
        this.nextSearchOffset = Utilities.getRowStart (doc, offset);
    } catch (BadLocationException ex) {
        Logger.getLogger (AbstractTokenList.class.getName ()).log (Level.FINE, null, ex);
        this.nextSearchOffset = offset;
    }
}
 
Example 16
Source File: HtmlTypedBreakInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void insert(MutableContext context) throws BadLocationException {
    BaseDocument doc = (BaseDocument) context.getDocument();
    int offset = context.getBreakInsertOffset();
    
    TokenSequence<HTMLTokenId> ts = LexUtilities.getTokenSequence((BaseDocument)doc, offset, HTMLTokenId.language());
    if (ts == null) {
        return;
    }
    ts.move(offset);
    String closingTagName = null;
    int end = -1;
    if (ts.moveNext() && ts.token().id() == HTMLTokenId.TAG_OPEN_SYMBOL &&
            ts.token().text().toString().equals("</")) {
        if (ts.moveNext() && ts.token().id() == HTMLTokenId.TAG_CLOSE) {
            closingTagName = ts.token().text().toString();
            end = ts.offset()+ts.token().text().length();
            ts.movePrevious();
            ts.movePrevious();
        }
    }
    if (closingTagName == null) {
        return;
    }
    boolean foundOpening = false;
    if (ts.token().id() == HTMLTokenId.TAG_CLOSE_SYMBOL &&
            ts.token().text().toString().equals(">")) {
        while (ts.movePrevious()) {
            if (ts.token().id() == HTMLTokenId.TAG_OPEN) {
                if (ts.token().text().toString().equals(closingTagName)) {
                    foundOpening = true;
                }
                break;
            }
        }
    }
    if (foundOpening) {
        context.setText("\n\n", 1, 1);
        //reformat workaround -- the preferred 
        //context.setText("\n\n", 1, 1, 0, 2);
        //won't work as the reformatter will not reformat the line with the closing tag
        int from = Utilities.getRowStart(doc, offset);
        int to = Utilities.getRowEnd(doc, offset);
        reformat = new Position[]{doc.createPosition(from), doc.createPosition(to)};
    }
}
 
Example 17
Source File: TagBasedLexerFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void enterPressed() throws BadLocationException{
    BaseDocument doc = (BaseDocument) context.document();
    
    if (isTopLevelLanguage(doc)) {
        doc.putProperty(TransferData.ORG_CARET_OFFSET_DOCPROPERTY, new Integer(context.caretOffset()));
    }

    Integer dotPos = (Integer) doc.getProperty(TransferData.ORG_CARET_OFFSET_DOCPROPERTY);
    //assert dotPos != null;
    if(dotPos == null) {
        dotPos = context.caretOffset();
    }
    
    int origDotPos = dotPos.intValue() - 1; // dotPos - "\n".length()
    
    if (indexWithinCurrentLanguage(doc, origDotPos - 1)) {
        if (isSmartEnter(doc, dotPos)) {
            handleSmartEnter(context);
        } else {
            int newIndent = 0;
            int lineNumber = Utilities.getLineOffset(doc, dotPos);
            boolean firstRow = false;
            
            if (Utilities.getRowStart(doc, origDotPos) == origDotPos){
                newIndent = getExistingIndent(doc, lineNumber);
                firstRow = true;
            } else if (lineNumber > 0){
                newIndent = getExistingIndent(doc, lineNumber - 1);
            }
            
            TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc);
            TokenSequence[] tokenSequences = (TokenSequence[]) tokenHierarchy.tokenSequenceList(supportedLanguagePath(), 0, Integer.MAX_VALUE).toArray(new TokenSequence[0]);
            TextBounds[] tokenSequenceBounds = new TextBounds[tokenSequences.length];
            
            for (int i = 0; i < tokenSequenceBounds.length; i++) {
                tokenSequenceBounds[i] = findTokenSequenceBounds(doc, tokenSequences[i]);
            }

            JoinedTokenSequence tokenSequence = new JoinedTokenSequence(tokenSequences, tokenSequenceBounds);
            tokenSequence.moveStart(); tokenSequence.moveNext();

            int openingTagOffset = getTagEndingAtPosition(tokenSequence, origDotPos - 1);
            
            if (isOpeningTag(tokenSequence, openingTagOffset)){
                newIndent += doc.getShiftWidth();
            }

            context.modifyIndent(Utilities.getRowStart(doc, dotPos), newIndent);
            
            if (firstRow){
                context.setCaretOffset(context.caretOffset() - newIndent);
            }
        }
    }
}
 
Example 18
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 19
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 20
Source File: ExtKit.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void comment(BaseDocument doc, int startOffset, int lineCount) throws BadLocationException {
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        doc.insertString(offset, lineCommentString, null); // NOI18N
        offset = Utilities.getRowStart(doc, offset, +1);
    }
}