Java Code Examples for javax.swing.text.Caret#setDot()

The following examples show how to use javax.swing.text.Caret#setDot() . 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: ElementResultItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * If called with <code>SHIFT_MASK</code> modified it createa a start tag and
 * end tag pair and place caret between them.
 */
public boolean substituteText( JTextComponent c, int offset, int len, int modifiers ){
    String replacementText = getReplacementText(modifiers);
    replaceText(c, replacementText, offset, len);
    
    boolean shift = (modifiers & java.awt.event.InputEvent.SHIFT_MASK) != 0;

    if (shift && startElement) {
        Caret caret = c.getCaret();  // it is at the end of replacement
        int dot = caret.getDot();
        int rlen = replacementText.length();
        if (empty) {
            caret.setDot((dot  - rlen) + replacementText.indexOf('/'));
        }
    }
    
    return false;
}
 
Example 2
Source File: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void testInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
Example 3
Source File: ApacheConfActionTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void testInFile(String file, String actionName) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    runKitAction(ta, actionName, null);

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, goldenFileExtension());
}
 
Example 4
Source File: Test6462562.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 5
Source File: Test6462562.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 6
Source File: EditorUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Set the position of the caret and scroll the extent if necessary.
 * @param offset position where the caret should be placed
 * @param scrollRect rectangle that should become visible. It can be null
 *   when no scrolling should be done.
 * @param scrollPolicy policy to be used when scrolling.
 * @deprecated
 */
public void caretSetDot(int offset, Rectangle scrollRect, int scrollPolicy) {
    if (component != null) {
        Caret caret = component.getCaret();
        if (caret instanceof BaseCaret) {
            ((BaseCaret)caret).setDot(offset, scrollRect, scrollPolicy);
        } else {
            caret.setDot(offset);
        }
    }
}
 
Example 7
Source File: CslTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void deleteWord(String original, String expected) throws Exception {
    String source = original;
    String reformatted = expected;
    Formatter formatter = getFormatter(null);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos+1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, null);

    runKitAction(ta, BaseKit.removePreviousWordAction, "\n");

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);
    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }

}
 
Example 8
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (!target.isEditable() || !target.isEnabled()) {
        target.getToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) target.getDocument();
    final Indent indenter = Indent.get(doc);
    final class R implements Runnable {
        public @Override void run() {
            try {
                Caret caret = target.getCaret();
                int dotpos = caret.getDot();
                int eoloffset = Utilities.getRowEnd(target, dotpos);
                doc.insertString(eoloffset, "" + what, null); //NOI18N
                if (withNewline) {
                    //This is code from the editor module, but it is
                    //a pretty strange way to do this:
                    doc.insertString(dotpos, "-", null); //NOI18N
                    doc.remove(dotpos, 1);
                    int eolDot = Utilities.getRowEnd(target, caret.getDot());
                    int newDotPos = indenter.indentNewLine(eolDot);
                    caret.setDot(newDotPos);
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    indenter.lock();
    try {
        doc.runAtomicAsUser(new R());
    } finally {
        indenter.unlock();
    }
}
 
Example 9
Source File: EditorFindSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void selectText(JTextComponent c, int start, int end, boolean back){
    Caret caret = c.getCaret();
    ensureVisible(c, start, end);
    if (back) {
        caret.setDot(end);
        caret.moveDot(start);
    } else { // forward direction
        caret.setDot(start);
        caret.moveDot(end);
    }
}
 
Example 10
Source File: CaretUndoEdit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void restoreLegacyCaret(Caret caret) {
    if (caret instanceof DefaultCaret) {
        ((DefaultCaret)caret).setDot(getOffset(dotOffsetAndBias), getBias(dotOffsetAndBias));
    } else {
        caret.setDot(getOffset(dotOffsetAndBias));
    }
}
 
Example 11
Source File: PhpCommentGeneratorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = PhpCommentGenerator.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
Example 12
Source File: ActionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        BaseDocument doc = (BaseDocument)target.getDocument();
        int dotPos = caret.getDot();
        int selectStartPos = -1;
        try {
            if (dotPos > 0) {
                if (doc.getChars(dotPos - 1, 1)[0] == ',') { // right after the comma
                    selectStartPos = dotPos;
                }
            }
            if (dotPos < doc.getLength()) {
                char dotChar = doc.getChars(dotPos, 1)[0];
                if (dotChar == ',') {
                    selectStartPos = dotPos + 1;
                } else if (dotChar == ')') {
                    caret.setDot(dotPos + 1);
                }
            }
            if (selectStartPos >= 0) {
                int selectEndPos = doc.find(
                                       new FinderFactory.CharArrayFwdFinder( new char[] { ',', ')' }),
                                       selectStartPos, -1
                                   );
                if (selectEndPos >= 0) {
                    target.select(selectStartPos, selectEndPos);
                }
            }
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}
 
Example 13
Source File: Test6462562.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 14
Source File: Test6462562.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

    Caret caret = getCaret();
    caret.setDot(pos);
    if (selectionLength > 0) {
        caret.moveDot(pos + selectionLength);
    }

    String desc = todo;
    if (todo == BACKSPACE) {
        backspace.actionPerformed(dummyEvent);
    } else if (todo == DELETE) {
        delete.actionPerformed(dummyEvent);
    } else {
        desc = "insert('" + todo + "')";
        insert.actionPerformed(new ActionEvent(this, 0, todo));
    }

    try {
        commitEdit();
    } catch (ParseException e) {
        e.printStackTrace();
        failed = true;
        return false;
    }

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example 15
Source File: GotoAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    String actionName = actionName();
    if (EditorActionNames.gotoDeclaration.equals(actionName)) {
        resetCaretMagicPosition(target);
        if (target != null) {
            if (hyperlinkGoTo(target)) {
                return;
            }
            
            BaseDocument doc = Utilities.getDocument(target);
            if (doc != null) {
                try {
                    Caret caret = target.getCaret();
                    int dotPos = caret.getDot();
                    int[] idBlk = Utilities.getIdentifierBlock(doc, dotPos);
                    ExtSyntaxSupport extSup = (ExtSyntaxSupport) doc.getSyntaxSupport();
                    if (idBlk != null) {
                        int decPos = extSup.findDeclarationPosition(doc.getText(idBlk), idBlk[1]);
                        if (decPos >= 0) {
                            caret.setDot(decPos);
                        }
                    }
                } catch (BadLocationException e) {
                }
            }
        }
    }
}
 
Example 16
Source File: TwigTypedTextInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void completeOpeningDelimiter(Document doc, int tokenEndPos, int dotPos, Caret caret, String closingDelimiter) throws BadLocationException {
    doc.insertString(tokenEndPos, closingDelimiter, null);
    caret.setDot(dotPos);
}
 
Example 17
Source File: PHPNewLineIndenterQATest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(indentPrefs);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, indentPrefs);

    Map<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults());
    options.put(FmtOptions.INITIAL_INDENT, initialIndent);
    if (indentPrefs != null) {
        options.put(FmtOptions.INDENT_SIZE, indentPrefs.getIndentation());
    }
    Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
    for (String option : options.keySet()) {
        Object value = options.get(option);
        if (value instanceof Integer) {
            prefs.putInt(option, ((Integer) value).intValue());
        } else if (value instanceof String) {
            prefs.put(option, (String) value);
        } else if (value instanceof Boolean) {
            prefs.put(option, ((Boolean) value).toString());
        } else if (value instanceof CodeStyle.BracePlacement) {
            prefs.put(option, ((CodeStyle.BracePlacement) value).name());
        } else if (value instanceof CodeStyle.WrapStyle) {
            prefs.put(option, ((CodeStyle.WrapStyle) value).name());
        }
    }

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    if (indentPrefs != null) {
        assertDescriptionMatches(file, target, false,
                "."
                + indentPrefs.getIndentation()
                + "_"
                + indentPrefs.getHangingIndentation()
                + "_" + initialIndent
                + ".indented");
    } else {
        assertDescriptionMatches(file, target, false, ".indented");
    }
}
 
Example 18
Source File: YamlKeystrokeHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public int beforeBreak(Document document, int offset, JTextComponent target) throws BadLocationException {

    Caret caret = target.getCaret();
    BaseDocument doc = (BaseDocument) document;

    // Very simple algorithm for now..
    // Basically, use the same indent as the current line, unless the caret is immediately preceeded by a ":" (possibly with whitespace
    // in between)

    int lineBegin = Utilities.getRowStart(doc, offset);
    int lineEnd = Utilities.getRowEnd(doc, offset);

    if (lineBegin == offset && lineEnd == offset) {
        // Pressed return on a blank newline - do nothing
        return -1;
    }

    int indent = getLineIndent(doc, offset);
    String linePrefix = doc.getText(lineBegin, offset - lineBegin);
    String lineSuffix = doc.getText(offset, lineEnd + 1 - offset);
    if (linePrefix.trim().endsWith(":") && lineSuffix.trim().length() == 0) {
        // Yes, new key: increase indent
        indent += IndentUtils.getIndentSize(doc);
    } else {
        // No, just use same indent as parent
    }

    // Also remove the whitespace from the caret up to the first nonspace character on the current line
    int remove = 0;
    String line = doc.getText(lineBegin, lineEnd + 1 - lineBegin);
    for (int n = line.length(), i = offset - lineBegin; i < n; i++) {
        char c = line.charAt(i);
        if (c == ' ' || c == '\t') {
            remove++;
        } else {
            break;
        }
    }
    if (remove > 0) {
        doc.remove(offset, remove);
    }
    String str = IndentUtils.getIndentString(indent);
    int newPos = offset + str.length();
    doc.insertString(offset, str, null);
    caret.setDot(offset);
    return newPos + 1;
}
 
Example 19
Source File: AddCaretSelectAllAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        if (!Utilities.isSelectionShowing(caret)) {
            try {
                int[] identifierBlock = Utilities.getIdentifierBlock((BaseDocument) target.getDocument(), caret.getDot());
                if (identifierBlock != null) {
                    caret.setDot(identifierBlock[0]);
                    caret.moveDot(identifierBlock[1]);
                }
            } catch (BadLocationException e) {
                LOGGER.log(Level.WARNING, null, e);
            }
        }

        EditorFindSupport findSupport = EditorFindSupport.getInstance();
        HashMap<String, Object> props = new HashMap<>(findSupport.createDefaultFindProperties());
        String searchWord = target.getSelectedText();
        if (searchWord != null) {
            int n = searchWord.indexOf('\n');
            if (n >= 0) {
                searchWord = searchWord.substring(0, n);
            }
            props.put(EditorFindSupport.FIND_WHAT, searchWord);
            Document doc = target.getDocument();
            EditorUI eui = org.netbeans.editor.Utilities.getEditorUI(target);
            if (eui.getComponent().getClientProperty("AsTextField") == null) { //NOI18N
                findSupport.setFocusedTextComponent(eui.getComponent());
            }
            findSupport.putFindProperties(props);
            findSupport.find(null, false);

            if (caret instanceof EditorCaret) {
                EditorCaret editorCaret = (EditorCaret) caret;
                try {
                    int[] blocks = findSupport.getBlocks(new int[]{-1, -1}, doc, 0, doc.getLength());
                    if (blocks[0] >= 0 && blocks.length % 2 == 0) {
                        List<Position> newCarets = new ArrayList<>();

                        for (int i = 0; i < blocks.length; i += 2) {
                            int start = blocks[i];
                            int end = blocks[i + 1];
                            if (start == -1 || end == -1) {
                                break;
                            }
                            Position startPos = doc.createPosition(start);
                            Position endPos = doc.createPosition(end);
                            newCarets.add(endPos);
                            newCarets.add(startPos);
                        }

                        editorCaret.replaceCarets(newCarets, null); // TODO handle biases
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
}
 
Example 20
Source File: GroovyTypedTextInterceptor.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**
 * A hook to be called after closing bracket ) or ] was inserted into
 * the document. The method checks if the bracket should stay there
 * or be removed and some exisitng bracket just skipped.
 *
 * @param doc the document
 * @param dotPos position of the inserted bracket
 * @param caret caret
 * @param bracket the bracket character ']' or ')'
 */
private void skipClosingBracket(BaseDocument doc, Caret caret, char bracket, TokenId bracketId)
    throws BadLocationException {
    int caretOffset = caret.getDot();

    if (isSkipClosingBracket(doc, caretOffset, bracketId)) {
        doc.remove(caretOffset - 1, 1);
        caret.setDot(caretOffset); // skip closing bracket
    }
}