Java Code Examples for javax.swing.JEditorPane#getCaret()

The following examples show how to use javax.swing.JEditorPane#getCaret() . 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: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void testCursorInFile(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 2
Source File: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected 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: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line of the caret in the most recent editor.
 * This returns the current line in the current editor if there's one,
 * or a line of the caret in the editor, that was most recently active.
 * @return the line or <code>null</code> when there was no recent active editor.
 */
public Line getMostRecentLine() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return null;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return null;
    StyledDocument d = e.getDocument ();
    if (d == null) return null;
    Caret caret = ep.getCaret ();
    if (caret == null) return null;
    int lineNumber = NbDocument.findLineNumber(d, caret.getDot());
    Line.Set lineSet = e.getLineSet();
    try {
        return lineSet.getCurrent(lineNumber);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
 
Example 4
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns identifier currently selected in editor or <code>null</code>.
 *
 * @return identifier currently selected in editor or <code>null</code>
 */
@Override
public String getSelectedIdentifier () {
    JEditorPane ep = contextDispatcher.getCurrentEditor ();
    if (ep == null) {
        return null;
    }
    Caret caret = ep.getCaret();
    if (caret == null) {
        // No caret => no selected text
        return null;
    }
    String s = ep.getSelectedText ();
    if (s == null) {
        return null;
    }
    if (Utilities.isJavaIdentifier (s)) {
        return s;
    }
    return null;
}
 
Example 5
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getSelectedText(JEditorPane pane, int offset) {
    if (pane != null
            && pane.getCaret() != null
            && pane.getSelectionStart() <= offset
            && offset <= pane.getSelectionEnd()) {
        return pane.getSelectedText();
    }
    return null;
}
 
Example 6
Source File: StyledEditorKit.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
Example 7
Source File: WatchPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static int getRecentColumn() {
    JEditorPane mostRecentEditor = EditorContextDispatcher.getDefault().getMostRecentEditor();
    if (mostRecentEditor != null) {
        Caret caret = mostRecentEditor.getCaret();
        if (caret != null) {
            int offset = caret.getDot();
            try {
                int rs = javax.swing.text.Utilities.getRowStart(mostRecentEditor, offset);
                return offset - rs;
            } catch (BadLocationException blex) {}
        }
    }
    return 0;
}
 
Example 8
Source File: StyledEditorKit.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
Example 9
Source File: JsCommentGeneratorTest.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 = JsDocumentationCompleter.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 10
Source File: JsCommentGeneratorEmbeddedTest.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 = JsDocumentationCompleter.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 11
Source File: JadeIndenterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private 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);

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

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

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".indented");
}
 
Example 12
Source File: StyledEditorKit.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
Example 13
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 14
Source File: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void testSelectionInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePosStart = source.indexOf('^');
    assertNotNull(sourcePosStart);
    int sourcePosEnd = source.lastIndexOf('^');
    assertNotNull(sourcePosEnd);
    String sourceWithoutMarkers = source.substring(0, sourcePosStart) + source.substring(sourcePosStart + 1, sourcePosEnd) + source.substring(sourcePosEnd + 1);

    JEditorPane ta = getPane(sourceWithoutMarkers);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePosStart);
    ta.setSelectionStart(sourcePosStart);
    ta.setSelectionEnd(sourcePosEnd - 1);
    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 15
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns number of line currently selected in editor or <code>-1</code>.
 *
 * @return number of line currently selected in editor or <code>-1</code>
 */
public int getCurrentOffset () {
    JEditorPane ep = contextDispatcher.getCurrentEditor();
    if (ep == null) {
        return -1;
    }
    Caret caret = ep.getCaret ();
    if (caret == null) {
        return -1;
    }
    return caret.getDot();
}
 
Example 16
Source File: StyledEditorKit.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
Example 17
Source File: StyledEditorKit.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
Example 18
Source File: CloneableEditorSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Forcibly create one editor component. Then set the caret
* to the given position.
* @param pos where to place the caret
* @param column where to place the caret
* @param reuse if true, the infrastructure tries to reuse other, already opened editor
 * for the purpose of opening this file/line. 
* @return always non-<code>null</code> editor
*/
private final Pane openAtImpl(final PositionRef pos, final int column, boolean reuse) {
    CloneableEditorSupport redirect = CloneableEditorSupportRedirector.findRedirect(this);
    if (redirect != null) {
        return redirect.openAtImpl(pos, column, reuse);
    }
    final Pane e = openPane(reuse);
    final Task t = prepareDocument();
    e.ensureVisible();
    class Selector implements TaskListener, Runnable {
        private boolean documentLocked = false;

        public void taskFinished(org.openide.util.Task t2) {
            javax.swing.SwingUtilities.invokeLater(this);
            t2.removeTaskListener(this);
        }

        public void run() {
            // #25435. Pane can be null.
            JEditorPane ePane = e.getEditorPane();

            if (ePane == null) {
                return;
            }

            StyledDocument doc = getDocument();

            if (doc == null) {
                return; // already closed or error loading
            }

            if (!documentLocked) {
                documentLocked = true;
                doc.render(this);
            } else {
                Caret caret = ePane.getCaret();

                if (caret == null) {
                    return;
                }

                int offset;

                // Pane's document may differ - see #204980
                Document paneDoc = ePane.getDocument();
                if (paneDoc instanceof StyledDocument && paneDoc != doc) {
                    if (ERR.isLoggable(Level.FINE)) {
                        ERR.fine("paneDoc=" + paneDoc + "\n !=\ndoc=" + doc); // NOI18N
                    }
                    doc = (StyledDocument) paneDoc;
                }

                javax.swing.text.Element el = NbDocument.findLineRootElement(doc);
                el = el.getElement(el.getElementIndex(pos.getOffset()));
                offset = el.getStartOffset() + Math.max(0, column);

                if (offset > el.getEndOffset()) {
                    offset = Math.max(el.getStartOffset(), el.getEndOffset() - 1);
                }

                caret.setDot(offset);

                try { // scroll to show reasonable part of the document
                    Rectangle r = ePane.modelToView(offset);
                    if (r != null) {
                        r.height *= 5;
                        ePane.scrollRectToVisible(r);
                    }
                } catch (BadLocationException ex) {
                    ERR.log(Level.WARNING, "Can't scroll to text: pos.getOffset=" + pos.getOffset() //NOI18N
                        + ", column=" + column + ", offset=" + offset //NOI18N
                        + ", doc.getLength=" + doc.getLength(), ex); //NOI18N
                }
            }
        }
    }
    t.addTaskListener(new Selector());

    return e;
}
 
Example 19
Source File: PHPNewLineIndenterTest.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());
    assertDescriptionMatches(file, target, false, ".indented");
}
 
Example 20
Source File: CompletionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void exec(JEditorPane editor, TestStep step) throws Exception {
    try {
        BaseDocument doc = (BaseDocument) editor.getDocument();
        ref(step.toString());
        Caret caret = editor.getCaret();
        caret.setDot(step.getOffset() + 1);
        EditorOperator eo = new EditorOperator(testFileObj.getNameExt());
        eo.insert(step.getPrefix());
        if (!isJavaScript()) {
            caret.setDot(step.getCursorPos());
        }

        waitTypingFinished(doc);
        CompletionJListOperator comp = null;
        boolean print = false;
        int counter = 0;
        while (!print) {
            ++counter;
            if (counter > 5) {
                print = true;
            }
            try {
                comp = CompletionJListOperator.showCompletion();
            } catch (JemmyException e) {
                log("EE: The CC window did not appear");
                e.printStackTrace(getLog());
            }
            if (comp != null) {
                print = dumpCompletion(comp, step, editor, print) || print;
                waitTypingFinished(doc);
                CompletionJListOperator.hideAll();
                if (!print) {// wait for refresh
                    Thread.sleep(1000);
                    if (!isJavaScript()) {
                        caret.setDot(step.getCursorPos());
                    }
                }
            } else {
                long time = System.currentTimeMillis();
                String screenFile = time + "-screen.png";
                log("CompletionJList is null");
                log("step: " + step);
                log("captureScreen:" + screenFile);
                try {
                    PNGEncoder.captureScreen(getWorkDir().getAbsolutePath() + File.separator + screenFile);
                } catch (Exception e1) {
                    e1.printStackTrace(getLog());
                }
            }
        }
        waitTypingFinished(doc);
        int rowStart = Utilities.getRowStart(doc, step.getOffset() + 1);
        int rowEnd = Utilities.getRowEnd(doc, step.getOffset() + 1);
        String fullResult = doc.getText(new int[]{rowStart, rowEnd});
        String result = fullResult.trim();
        int removed_whitespaces = fullResult.length() - result.length();
        if (!result.equals(step.getResult().trim())) {
            ref("EE: unexpected CC result:\n< " + result + "\n> " + step.getResult());
        }
        ref("End cursor position = " + (caret.getDot() - removed_whitespaces));
    } finally {
        // undo all changes
        final UndoAction ua = SystemAction.get(UndoAction.class);
        assertNotNull("Cannot obtain UndoAction", ua);
        while (ua.isEnabled()) {
            runInAWT(new Runnable() {

                public void run() {
                    ua.performAction();
                }
            });
        }
    }
}