Java 类javax.swing.text.Caret 实例源码

项目:powertext    文件:AutoCompletePopupWindow.java   
@Override
public void actionPerformed(ActionEvent e) {
    if (isVisible()) {
        JTextComponent comp = ac.getTextComponent();
        Caret c = comp.getCaret();
        int dot = c.getDot();
        if (dot < comp.getDocument().getLength()) {
            c.setDot(++dot);
            // Ensure moving right hasn't moved us up a line, thus
            // hiding the popup window.
            if (comp.isVisible()) {
                if (lastLine!=-1) {
                    doAutocomplete();
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:SQLHistoryPanel.java   
private int insertIntoDocument(String s, JEditorPane target)
        throws BadLocationException {
    Document doc = target.getDocument();
    if (s == null) {
        s = "";
        }
    if (doc == null) {
        return -1;
    }        
    int start = -1;
    try {
        Caret caret = target.getCaret();
        int p0 = Math.min(caret.getDot(), caret.getMark());
        int p1 = Math.max(caret.getDot(), caret.getMark());
        doc.remove(p0, p1 - p0);
        start = caret.getDot();
        doc.insertString(start, s + ";\n", null); // NOI18N
    } catch (BadLocationException ble) {
        LOGGER.log(Level.WARNING, org.openide.util.NbBundle.getMessage(SQLHistoryPanel.class, "LBL_InsertAtLocationError") + ble);
}
    return start;
}
项目:incubator-netbeans    文件:ElementResultItem.java   
/**
 * 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;
}
项目:incubator-netbeans    文件:MethodChooser.java   
/**
 * Ends the method selection mode, clears all used ui elements. Notifies each registered
 * {@link ReleaseListener}.
 *
 * @param performAction <code>true</code> indicates that the current selection should
 *          be used to perform an action, <code>false</code> means that the selection mode
 *          has beencancelled
 */
public synchronized void releaseUI(boolean performAction) {
    if (!isInSelectMode) {
        return; // do nothing
    }
    getHighlightsBag(doc).clear();
    editorPane.removeKeyListener(mainListener);
    editorPane.removeMouseListener(mainListener);
    editorPane.removeMouseMotionListener(mainListener);
    editorPane.removeFocusListener(mainListener);
    editorPane.putClientProperty(MethodChooser.class, null);
    editorPane.setCursor(originalCursor);
    Caret caret = editorPane.getCaret();
    if (caret instanceof BaseCaret) {
        ((BaseCaret)caret).setVisible(true);
    }

    if (hintText != null && hintText.trim().length() > 0) {
        Utilities.clearStatusText(editorPane);
    }
    isInSelectMode = false;
    for (ReleaseListener listener : releaseListeners) {
        listener.released(performAction);
    }
}
项目:incubator-netbeans    文件:BaseKit.java   
public void actionPerformed(final ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        final Caret caret = target.getCaret();
        final BaseDocument doc = (BaseDocument)target.getDocument();
        doc.render(new Runnable () {
            public void run () {
                DocumentUtilities.setTypingModification(doc, true);
                try {
                    int dotPos = caret.getDot();
                    int bolPos = Utilities.getRowStart(target, dotPos);
                    int eolPos = Utilities.getRowEnd(target, dotPos);
                    eolPos = Math.min(eolPos + 1, doc.getLength()); // include '\n'
                    caret.setDot(bolPos);
                    caret.moveDot(eolPos);
                } catch (BadLocationException e) {
                    target.getToolkit().beep();
                } finally {
                    DocumentUtilities.setTypingModification(doc, false);
                }
            }
        });
    }
}
项目:incubator-netbeans    文件:GotoBookmarkAction.java   
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        BookmarkList bookmarkList = BookmarkList.get(target.getDocument());
        int dotOffset = caret.getDot();
        Bookmark bookmark = gotoNext
            ? bookmarkList.getNextBookmark(dotOffset, true) // next (wrap)
            : bookmarkList.getPreviousBookmark(dotOffset, true); // previous (wrap)

        if (bookmark != null) {
            if (select) {
                caret.moveDot(bookmark.getOffset());
            } else {
                caret.setDot(bookmark.getOffset());
            }
        }
    }
}
项目:incubator-netbeans    文件:ActionFactory.java   
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        try {
            int pos = Utilities.getRowFirstNonWhite((BaseDocument)target.getDocument(),
                                                    caret.getDot());
            if (pos >= 0) {
                boolean select = BaseKit.selectionFirstNonWhiteAction.equals(getValue(Action.NAME));
                if (select) {
                    caret.moveDot(pos);
                } else {
                    caret.setDot(pos);
                }
            }
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}
项目:incubator-netbeans    文件:ActionFactory.java   
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        try {
            int pos = Utilities.getRowLastNonWhite((BaseDocument)target.getDocument(),
                                                   caret.getDot());
            if (pos >= 0) {
                boolean select = BaseKit.selectionLastNonWhiteAction.equals(getValue(Action.NAME));
                if (select) {
                    caret.moveDot(pos);
                } else {
                    caret.setDot(pos);
                }
            }
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}
项目:incubator-netbeans    文件:ActionFactory.java   
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled()) {
            target.getToolkit().beep();
            return;
        }

        try {
            Caret caret = target.getCaret();
            BaseDocument doc = (BaseDocument)target.getDocument();

            // Format the current time.
            SimpleDateFormat formatter = new SimpleDateFormat();
            Date currentTime = new Date();
            String dateString = formatter.format(currentTime);

            doc.insertString(caret.getDot(), dateString, null);
        } catch (BadLocationException e) {
            target.getToolkit().beep();
        }
    }
}
项目:incubator-netbeans    文件:BaseCaret.java   
/**
 * Determines if the following are true:
 * <ul>
 * <li>the press event is located over a selection
 * <li>the dragEnabled property is true
 * <li>A TranferHandler is installed
 * </ul>
 * <p>
 * This is implemented to check for a TransferHandler.
 * Subclasses should perform the remaining conditions.
 */
protected boolean isDragPossible(MouseEvent e) {
    JComponent comp = getEventComponent(e);
    boolean possible =  (comp == null) ? false : (comp.getTransferHandler() != null);
    if (possible) {
        JTextComponent c = (JTextComponent) getEventComponent(e);
        if (c.getDragEnabled()) {
            Caret caret = c.getCaret();
            int dot = caret.getDot();
            int mark = caret.getMark();
            if (dot != mark) {
                Point p = new Point(e.getX(), e.getY());
                int pos = c.viewToModel(p);

                int p0 = Math.min(dot, mark);
                int p1 = Math.max(dot, mark);
                if ((pos >= p0) && (pos < p1)) {
                    return true;
                }
            }
        }
    }
    return false;
}
项目:incubator-netbeans    文件:Utilities.java   
/** Get the selection if there's any or get the identifier around
   * the position if there's no selection.
   */
   public static String getSelectionOrIdentifier(JTextComponent c, int offset)
   throws BadLocationException {
       Document doc = c.getDocument();
       Caret caret = c.getCaret();
       String ret;
       if (Utilities.isSelectionShowing(caret)) {
           ret = c.getSelectedText();
    if (ret != null) return ret;
       } 
if (doc instanceof BaseDocument){
    ret = getIdentifier((BaseDocument) doc, offset);
       } else {
    ret = getWord(c, offset);
}
       return ret;
   }
项目:incubator-netbeans    文件:ExtKit.java   
public boolean gotoDeclaration(JTextComponent target) {
    BaseDocument doc = Utilities.getDocument(target);
    if (doc == null)
        return false;
    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);
                return true;
            }
        }
    } catch (BadLocationException e) {
    }
    return false;
}
项目:incubator-netbeans    文件:ExtKit.java   
public @Override void actionPerformed(ActionEvent evt, JTextComponent target) {
    String cmd = evt.getActionCommand();
    int mod = evt.getModifiers();

    // Dirty fix for Completion shortcut on Unix !!!
    if (cmd != null && cmd.equals(" ") && (mod == ActionEvent.CTRL_MASK)) { // NOI18N
        // Ctrl + SPACE
    } else {
        Caret caret = target.getCaret();
        if (caret instanceof ExtCaret) {
            ((ExtCaret)caret).requestMatchBraceUpdateSync(); // synced bracket update
        }
        super.actionPerformed(evt, target);
    }

    if ((target != null) && (evt != null)) {
        if ((cmd != null) && (cmd.length() == 1)) {
            // Check whether char that should reindent the line was inserted
            checkIndentHotChars(target, cmd);

            // Check the completion
            checkCompletion(target, cmd);
        }
    }
}
项目:incubator-netbeans    文件:EditorContextDispatcher.java   
/**
 * 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;
    }
}
项目:incubator-netbeans    文件:CaretOverwriteModeHighlighting.java   
private void updateActiveCaret() {
    if (visible) {
        setVisible(false);
    }
    if (editorCaret != null) {
        editorCaret.removeEditorCaretListener(weakEditorCaretListener);
        weakEditorCaretListener = null;
        editorCaret = null;
        docText = null;
    }

    Caret caret = component.getCaret();
    if (caret instanceof EditorCaret) { // Only work for editor caret
        editorCaret = (EditorCaret) caret;
    }

    if (editorCaret != null) {
        updateDocText();
        weakEditorCaretListener = WeakListeners.create(EditorCaretListener.class, this, editorCaret);
        editorCaret.addEditorCaretListener(weakEditorCaretListener);
    }
}
项目:incubator-netbeans    文件:ActiveEditorDropDefaultProvider.java   
public boolean handleTransfer(JTextComponent targetComponent) {

            if (targetComponent == null)
                return false;

            try {
                Document doc = targetComponent.getDocument();
                Caret caret = targetComponent.getCaret();
                int p0 = Math.min(caret.getDot(), caret.getMark());
                int p1 = Math.max(caret.getDot(), caret.getMark());
                doc.remove(p0, p1 - p0);

                //replace selected text by the inserted one
                int start = caret.getDot();
                doc.insertString(start, body, null);
            }
            catch (BadLocationException ble) {
                return false;
            }

            return true;
        }
项目:incubator-netbeans    文件:SelectCodeElementAction.java   
private int computeSelIndex(boolean inner) {
    Caret caret = target.getCaret();
    if (selectionInfos != null && caret != null && caret.getDot() != caret.getMark()) {
        int dot = caret.getDot();
        int mark = caret.getMark();
        int start = Math.min(dot,mark);
        //int end = Math.max(dot,mark);
        for (int i = 0; i < selectionInfos.length; i++) {
            if (selectionInfos[i].getStartOffset() == start) {
                // TODO - check end offset too
                return i;
            }
        }
        // No exact match - look at the editor selection and find the range
        // that most closely surround the selection (if inner is true, go
        // for the inner one, otherwise the outer)
        for (int i = selectionInfos.length-2; i >= 0; i--) {
            if (selectionInfos[i].getStartOffset() > start &&
                    selectionInfos[i+1].getStartOffset() < start) {
                return inner ? i : i-1;
            }
        }
    }

    return selIndex;
}
项目:incubator-netbeans    文件:CslEditorKit.java   
@Override
protected void insertString(BaseDocument doc, int dotPos, Caret caret, String str,
    boolean overwrite) throws BadLocationException {
    if (completionSettingEnabled()) {
        KeystrokeHandler bracketCompletion = UiUtils.getBracketCompletion(doc, dotPos);

        if (bracketCompletion != null) {
            // TODO - check if we're in a comment etc. and if so, do nothing
            boolean handled =
                bracketCompletion.beforeCharInserted(doc, dotPos, currentTarget,
                    str.charAt(0));

            if (!handled) {
                super.insertString(doc, dotPos, caret, str, overwrite);
                handled = bracketCompletion.afterCharInserted(doc, dotPos, currentTarget,
                        str.charAt(0));
            }

            return;
        }
    }

    super.insertString(doc, dotPos, caret, str, overwrite);
}
项目:incubator-netbeans    文件:CslEditorKit.java   
@Override
protected void afterBreak(JTextComponent target, BaseDocument doc, Caret caret,
    Object cookie) {
    if (completionSettingEnabled()) {
        if (cookie != null) {
            if (cookie instanceof Integer) {
                // integer
                int dotPos = ((Integer)cookie).intValue();
                if (dotPos != -1) {
                    caret.setDot(dotPos);
                } else {
                    int nowDotPos = caret.getDot();
                    caret.setDot(nowDotPos + 1);
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:BracesMatchHighlighting.java   
private void refresh() {
    if (released) {
        return; // No longer notify the matcher since it would leak to memory leak of MasterMatcher.lastResult
    }

    Caret c = this.caret;
    if (c == null) {
        bag.clear();
    } else {
        MasterMatcher.get(component).highlight(
            document,
            c.getDot(), 
            bag, 
            bracesMatchColoring, 
            bracesMismatchColoring,
            bracesMatchMulticharColoring,
            bracesMismatchMulticharColoring
        );
    }
}
项目:incubator-netbeans    文件:EditorContextImpl.java   
/**
 * 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;
}
项目:incubator-netbeans    文件:SelectionAwareJavaSourceTaskFactory.java   
public void run() {
    Collection<JTextComponent> update;

    synchronized (this) {
        update = updateSelection;
        updateSelection = new HashSet<>();
    }
    for (JTextComponent c : update) {
        int selStart, selEnd;
        Caret caret = c.getCaret();
        // possobly the caret is not yet installed ?
        if (caret != null) {
            selStart = c.getSelectionStart();
            selEnd = c.getSelectionEnd();
        } else {
            selStart = selEnd = 0;
        }

        //TODO: are we in AWT Thread?:
        setLastSelection(OpenedEditors.getFileObject(c), selStart, selEnd);
    }
}
项目:incubator-netbeans    文件:FoldingEditorSupport.java   
public boolean equals(Object whatever) {
    if (!(whatever instanceof Caret)) {
        return super.equals(whatever);
    }
    sharp = false;
    final Document doc = component.getDocument();
    doc.render(this);
    return res;
}
项目:incubator-netbeans    文件:EditorUI.java   
public @Override void propertyChange(PropertyChangeEvent evt) {
    String propName = evt.getPropertyName();

    if ("document".equals(propName)) { // NOI18N
        BaseDocument oldDoc = (evt.getOldValue() instanceof BaseDocument)
                              ? (BaseDocument)evt.getOldValue() : null;
        BaseDocument newDoc = (evt.getNewValue() instanceof BaseDocument)
                              ? (BaseDocument)evt.getNewValue() : null;
        modelChanged(oldDoc, newDoc);

    } else if ("margin".equals(propName)) { // NOI18N
        updateTextMargin();

    } else if ("caret".equals(propName)) { // NOI18N
        if (evt.getOldValue() instanceof Caret) {
            ((Caret)evt.getOldValue()).removeChangeListener(this);
        }
        if (evt.getNewValue() instanceof Caret) {
            ((Caret)evt.getNewValue()).addChangeListener(this);
        }

    } else if ("enabled".equals(propName)) { // NOI18N
        if (!component.isEnabled()) {
            component.getCaret().setVisible(false);
        }
    } else if (EditorUtilities.CARET_OVERWRITE_MODE_PROPERTY.equals(propName)) {
        // Mirror the property into EditorUI
        putProperty(OVERWRITE_MODE_PROPERTY, component.getClientProperty(EditorUtilities.CARET_OVERWRITE_MODE_PROPERTY));
    }

    if (propName == null || ColoringMap.PROP_COLORING_MAP.equals(propName)) {
        listener.preferenceChange(null);
    }
}
项目:incubator-netbeans    文件:EditorUI.java   
/** 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 caretMoveDot(int offset, Rectangle scrollRect, int scrollPolicy) {
    if (component != null) {
        Caret caret = component.getCaret();
        if (caret instanceof BaseCaret) {
            ((BaseCaret)caret).moveDot(offset, scrollRect, scrollPolicy);
        } else {
            caret.moveDot(offset);
        }
    }
}
项目:powertext    文件:RTextAreaEditorKit.java   
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
    if (!textArea.isEditable() || !textArea.isEnabled()) {
        UIManager.getLookAndFeel().provideErrorFeedback(textArea);
        return;
    }
    try {
        Caret c = textArea.getCaret();
        int caretPos = c.getDot();
        Document doc = textArea.getDocument();
        Element map = doc.getDefaultRootElement();
        int lineCount = map.getElementCount();
        int line = map.getElementIndex(caretPos);
        if (line==lineCount-1) {
            UIManager.getLookAndFeel().
                        provideErrorFeedback(textArea);
            return;
        }
        Element lineElem = map.getElement(line);
        caretPos = lineElem.getEndOffset() - 1;
        c.setDot(caretPos);     // Gets rid of any selection.
        doc.remove(caretPos, 1);    // Should be '\n'.
    } catch (BadLocationException ble) {
        /* Shouldn't ever happen. */
        ble.printStackTrace();
    }
    textArea.requestFocusInWindow();
}
项目:incubator-netbeans    文件:BaseKit.java   
private int computeInsertionOffset(Caret caret) {
    if (Utilities.isSelectionShowing(caret)) {
        return Math.min(caret.getMark(), caret.getDot());
    } else {
        return caret.getDot();
    }
}
项目:jdk8u-jdk    文件:Test6462562.java   
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;
}
项目:incubator-netbeans    文件:PropertiesTableCellEditor.java   
/**
* It sets the cursot at the beginnig of edited cell, in case of searching it highlights the found text.
* At the end it request for focus so the editor component (JTextField) has it, not the table.
* This is also a hack with reason to figure out which cell is going to be edited, if a key or a value.
*/
@Override
public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {

    // Key or value? Only in the first column are keys.
    isKeyCell = (column == 0) ? true : false;

    valueComponent.getDocument().removeDocumentListener(listener);
    commentComponent.getDocument().removeDocumentListener(listener);
    final JTextField textField = (JTextField)super.getTableCellEditorComponent(table, value, isSelected, row, column);
    valueComponent.getDocument().addDocumentListener(listener);
    commentComponent.getDocument().addDocumentListener(listener);
    Caret caret = textField.getCaret();
    caret.setVisible(true);
    caret.setDot(0);

    textField.setFont(settings.getFont());

    // Check for search results.
    // If search was performed, highlight the found string.
    int[] result = (int[])table.getClientProperty(FindPerformer.TABLE_SEARCH_RESULT);
    if(result != null && row == result[0] && column == result[1]) {
        table.putClientProperty(FindPerformer.TABLE_SEARCH_RESULT, null); // removes property
        caret.setDot(result[2]);
        caret.moveDot(result[3]);
    }

    return textField;
}
项目:incubator-netbeans    文件:BaseKit.java   
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        try {
            Caret caret = target.getCaret();
            boolean emptySelection = false;
            boolean disableNoSelectionCopy =
                    Boolean.getBoolean("org.netbeans.editor.disable.no.selection.copy");
            int caretPosition = caret.getDot();
            if(!disableNoSelectionCopy &&
                    (!(caret instanceof EditorCaret)) || !(((EditorCaret)caret).getCarets().size() > 1)) {
                emptySelection = !Utilities.isSelectionShowing(target);
                // If there is no selection then pre-select a current line including newline
                if (emptySelection && !disableNoSelectionCopy) {
                    Element elem = ((AbstractDocument) target.getDocument()).getParagraphElement(
                            caretPosition);
                    if (!Utilities.isRowWhite((BaseDocument) target.getDocument(), elem.getStartOffset())) {
                        target.select(elem.getStartOffset(), elem.getEndOffset());
                    }
                }
            }
            target.copy();
            if (emptySelection && !disableNoSelectionCopy) {
                target.setCaretPosition(caretPosition);
            }
        } catch (BadLocationException ble) {
            LOG.log(Level.FINE, null, ble);
        }
    }
}
项目:incubator-netbeans    文件:MarkOccurrencesTest.java   
private void setAndCheck(int pos,SimpleMark[] marks) throws IOException {
    Caret c = editorPane.getCaret();
    c.setDot(pos);
    foundMarks=null;
    int cycles = 0;
    sleep(500);
    while(foundMarks==null && cycles<30) {
        sleep(200);
        cycles++;
        js.runUserActionTask(new MyTask() ,false);
    }        
    Arrays.sort(marks);        
    String etalon = "";
    for (int i = 0; i < marks.length; i++) {
        SimpleMark m = marks[i];
        etalon = etalon + "["+m.start+","+m.end+"] ";
    }
    String ref = "";
    //not locking, should be fine in tests:
    if(foundMarks==null) {
        ref = "";
    } else {            
        Collections.sort(foundMarks, new Comparator<int[]>(){

            public int compare(int[] o1, int[] o2) {
                if(o1[0]<o2[0]) return -1;
                if(o1[0]>o2[0]) return 1;
                if(o1[1]<o2[1]) return -1;
                if(o2[1]>o2[1]) return 1;                    
                return 0;
            }
        });
        for(int[] mark:foundMarks) {                
            ref = ref + "[" + mark[0] + "," + mark[1] + "] ";
        }
    }        
    assertEquals(etalon, ref);
}
项目:incubator-netbeans    文件:HtmlTypedTextInterceptor.java   
@Override
public boolean beforeInsert(Context context) throws BadLocationException {
    int dotPos = context.getOffset();
    Caret caret = context.getComponent().getCaret();
    char ch = context.getText().charAt(0);

    //"ignore typed text support" 
    //depending on previous actions we are 
    //going to ignore some characters typed
    if (insertIgnore != null) {
        DocumentInsertIgnore local = insertIgnore;
        insertIgnore = null;
        if (local.getOffset() == dotPos && local.getChar() == ch) {
            //move the caret to specified position if needed
            if (local.getMoveCaretTo() != -1) {
                caret.setDot(local.moveCaretTo);
                //also close the completion window
                Completion.get().hideAll();
            }
            return true; //stop subsequent processing of the change
        }
    } else {
        //normal before key typed processing
        switch (ch) {
            case '\'':
            case '"':
                boolean result = skipExistingQuote(context);
                if (!result) {
                    result = changeQuotesType(context);
                }
                return result;
        }
    }
    return false;
}
项目:incubator-netbeans    文件:CommentsPanel.java   
private void setupTextPane(final JTextPane textPane, String comment) {
    if( UIUtils.isNimbus() ) {
        textPane.setUI( new BasicTextPaneUI() );
    }
    textPane.setText(comment);

    Caret caret = textPane.getCaret();
    if (caret instanceof DefaultCaret) {
        ((DefaultCaret)caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    }

    // attachments
    if (!attachmentIds.isEmpty()) {
        AttachmentHyperlinkSupport.Attachement a = AttachmentHyperlinkSupport.findAttachment(comment, attachmentIds);
        if (a != null) {
            String attachmentId = a.id;
            if (attachmentId != null) {
                int index = attachmentIds.indexOf(attachmentId);
                if (index != -1) {
                    BugzillaIssue.Attachment attachment = attachments.get(index);
                    AttachmentLink attachmentLink = new AttachmentLink(attachment);
                    HyperlinkSupport.getInstance().registerLink(textPane, new int[] {a.idx1, a.idx2}, attachmentLink);
                } else {
                    Bugzilla.LOG.log(Level.WARNING, "couldn''t find attachment id in: {0}", comment); // NOI18N
                }
            }
        }
    }

    // pop-ups
    textPane.setComponentPopupMenu(commentsPopup);

    textPane.setBackground(blueBackground);

    textPane.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
    textPane.setEditable(false);
    textPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleName")); // NOI18N
    textPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleDescription")); // NOI18N
}
项目:JavaGraph    文件:MultiLinedEditor.java   
@Override
public void run() {
    getEditorComponent().removeCaretListener(RealCellEditor.this);
    Caret caret = getEditorComponent().getCaret();
    int pos = Math.min(caret.getDot(), caret.getMark());
    getEditorComponent().replaceSelection(this.completion);
    getEditorComponent().setCaretPosition(pos);
    getEditorComponent().moveCaretPosition(pos + this.completion.length());
    getEditorComponent().addCaretListener(RealCellEditor.this);
}
项目:incubator-netbeans    文件:GotoAction.java   
@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) {
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:Abbrev.java   
/**
 * Test whether the abbreviation expansion is disabled
 * at the caret position in the given component's document.
 * 
 * @param component non-null text component.
 * @return true if the abbreviation can be expanded or false if not.
 */
public static boolean isAbbrevDisabled(JTextComponent component) {
    Document doc = component.getDocument();
    if (doc instanceof BaseDocument) {
        BaseDocument bdoc = (BaseDocument)doc;
        SyntaxSupport sup = bdoc.getSyntaxSupport();
        if (sup != null) {
            Caret caret = component.getCaret();
            return sup.isAbbrevDisabled(caret != null ? caret.getDot() : 0);
        }
    }
    return false; // abbrev not disabled
}
项目:incubator-netbeans    文件:Abbrev.java   
public String getExpandString() {
    BaseDocument doc = (BaseDocument)editorUI.getDocument();
    String abbrevStr = getAbbrevString();
    int abbrevStrLen = abbrevStr.length();
    Object expansion = translateAbbrev(abbrevStr);
    Caret caret = editorUI.getComponent().getCaret();
    int dotPos = caret.getDot();
    if (abbrevStr != null && expansion != null
            && dotPos >= abbrevStrLen
       ) {
        if (checkDocText) {
            try {
                CharSequence prevChars = DocumentUtilities.getText(doc, dotPos - abbrevStrLen, abbrevStrLen);
                if (CharSequenceUtilities.textEquals(prevChars, abbrevStr)) { // abbrev chars really match text
                    if (!checkTextDelimiter || dotPos == abbrevStrLen
                            || resetAcceptor.accept(
                                doc.getChars(dotPos - abbrevStrLen - 1, 1)[0])
                       ) {
                        return abbrevStr;
                    }
                }
            } catch (BadLocationException e) {
            }
        }
    }
    return null;
}
项目:incubator-netbeans    文件:DocumentationScrollPane.java   
private void copy() {
    Caret caret = view.getCaret();
    if (caret.getDot() != caret.getMark()) {
        view.copy();
    } else {
        editorComponent.copy();
    }
}
项目:incubator-netbeans    文件:ActionFactory.java   
public void actionPerformed(final ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled()) {
            target.getToolkit().beep();
            return;
        }

        final Caret caret = target.getCaret();
        final BaseDocument doc = (BaseDocument)target.getDocument();
        doc.runAtomicAsUser (new Runnable () {
            public void run () {
                DocumentUtilities.setTypingModification(doc, true);
                try {
                    int dotPos = caret.getDot();
                    int bolPos = Utilities.getRowStart(doc, dotPos);
                    int wsPos = Utilities.getPreviousWord(target, dotPos);
                    wsPos = (dotPos == bolPos) ? wsPos : Math.max(bolPos, wsPos);
                    doc.remove(wsPos, dotPos - wsPos);
                } catch (BadLocationException e) {
                    target.getToolkit().beep();
                } finally {
                    DocumentUtilities.setTypingModification(doc, false);
                }
            }
        });
    }
}