Java Code Examples for javax.swing.text.JTextComponent#getCaret()

The following examples show how to use javax.swing.text.JTextComponent#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: DarkKeyTypedAction.java    From darklaf with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if ((target != null) && (e != null)) {
        if ((!target.isEditable()) || (!target.isEnabled())) {
            return;
        }
        String content = e.getActionCommand();
        Caret c = target.getCaret();
        if (c instanceof DarkCaret) {
            boolean isDelete = !content.isEmpty();
            if (isDelete) {
                char key = content.charAt(0);
                isDelete = key == KeyEvent.VK_DELETE || key == KeyEvent.VK_BACK_SPACE;
            }
            if (((DarkCaret) c).isInsertMode()) {
                ((DarkCaret) c).setExpandMode(!isDelete);
            }
            super.actionPerformed(e);
            ((DarkCaret) c).setExpandMode(false);
            return;
        }
    }
    super.actionPerformed(e);
}
 
Example 2
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public void actionPerformed(ActionEvent e) {
  JTextComponent target = getTextComponent(e);
  if (Objects.nonNull(target) && target.isEditable()) {
    Caret caret = target.getCaret();
    int dot = caret.getDot();
    int mark = caret.getMark();
    if (DefaultEditorKit.deletePrevCharAction.equals(getValue(Action.NAME))) {
      // @see javax/swing/text/DefaultEditorKit.java DeletePrevCharAction
      if (dot == 0 && mark == 0) {
        return;
      }
    } else {
      // @see javax/swing/text/DefaultEditorKit.java DeleteNextCharAction
      Document doc = target.getDocument();
      if (dot == mark && doc.getLength() == dot) {
        return;
      }
    }
  }
  deleteAction.actionPerformed(e);
}
 
Example 3
Source File: HtmlPaletteUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static int insert(String s, JTextComponent target, Document doc) 
throws BadLocationException 
{

    int start = -1;
    try {
        //at first, find selected text range
        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);
        
        //replace selected text by the inserted one
        start = caret.getDot();
        doc.insertString(start, s, null);
    }
    catch (BadLocationException ble) {}
    
    return start;
}
 
Example 4
Source File: ActionFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example 5
Source File: GotoBookmarkAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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());
            }
        }
    }
}
 
Example 6
Source File: ToggleInsertAction.java    From darklaf with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        Caret c = target.getCaret();
        if (c instanceof DarkCaret) {
            ((DarkCaret) c).setInsertMode(!((DarkCaret) c).isInsertMode());
        }
    }
}
 
Example 7
Source File: BracesMatchHighlighting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public BracesMatchHighlighting(JTextComponent component, Document document) {
    this.document = document;

    String mimeType = getMimeType(component);
    MimePath mimePath = mimeType == null ? MimePath.EMPTY : MimePath.parse(mimeType);

    // Load the colorings
    FontColorSettings fcs = MimeLookup.getLookup(mimePath).lookup(FontColorSettings.class);
    AttributeSet match = fcs.getFontColors(BRACES_MATCH_COLORING);
    AttributeSet mismatch = fcs.getFontColors(BRACES_MISMATCH_COLORING);
    AttributeSet matchMultichar = fcs.getFontColors(BRACES_MATCH_MULTICHAR_COLORING);
    AttributeSet mismatchMultichar = fcs.getFontColors(BRACES_MISMATCH_MULTICHAR_COLORING);
    this.bracesMatchColoring = match != null ? match : SimpleAttributeSet.EMPTY;
    this.bracesMismatchColoring = mismatch != null ? mismatch : SimpleAttributeSet.EMPTY;
    this.bracesMatchMulticharColoring = matchMultichar != null ? matchMultichar : SimpleAttributeSet.EMPTY;
    this.bracesMismatchMulticharColoring = mismatchMultichar != null ? mismatchMultichar : SimpleAttributeSet.EMPTY;
    
    // Create and hook up the highlights bag
    this.bag = new OffsetsBag(document, true);
    this.bag.addHighlightsChangeListener(this);
    
    // Hook up the component
    this.component = component;
    this.component.addPropertyChangeListener(WeakListeners.propertyChange(this, this.component));

    // Hook up the caret
    this.caret = component.getCaret();
    if (this.caret != null) {
        this.caretListener = WeakListeners.change(this, this.caret);
        this.caret.addChangeListener(caretListener);
    }

    // Refresh the layer
    refresh();
}
 
Example 8
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 9
Source File: HtmlCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean canFilter(JTextComponent component) {
    try {
        if (component.getCaret() == null || component.getCaretPosition() < anchor) {
            return false;
        }
        
        Document doc = component.getDocument();
        int offset = component.getCaretPosition();

        String prefix = doc.getText(anchor, offset - anchor);

        //check the items
        for (CompletionItem item : items) {
            if (item instanceof HtmlCompletionItem) {
                String itemText = ((HtmlCompletionItem) item).getItemText();
                if(itemText != null) { //http://netbeans.org/bugzilla/show_bug.cgi?id=222234
                    if (startsWithIgnoreCase(itemText, prefix)) {
                        return true; //at least one item will remain
                    }
                } else {
                    LOG.log(Level.WARNING, "CompletionItem {0} returned null from getItemText()!", item);
                }
            }
        }


    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return false;

}
 
Example 10
Source File: HighlightsViewUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static double getMagicX(DocumentView docView, EditorView view, int offset, Bias bias, Shape alloc) {
    JTextComponent textComponent = docView.getTextComponent();
    if (textComponent == null) {
        return 0d;
    }
    Caret caret = textComponent.getCaret();
    Point magicCaretPoint = null;
    if(caret != null) {
        if(caret instanceof EditorCaret) {
            EditorCaret editorCaret = (EditorCaret) caret;
            CaretInfo info = editorCaret.getCaretAt(offset);
            magicCaretPoint = (info != null) ? info.getMagicCaretPosition() : null;
        } else {
            magicCaretPoint = caret.getMagicCaretPosition();
        }
    }
    double x;
    if (magicCaretPoint == null) {
        Shape offsetBounds = view.modelToViewChecked(offset, alloc, bias);
        if (offsetBounds == null) {
            x = 0d;
        } else {
            x = offsetBounds.getBounds2D().getX();
        }
    } else {
        x = magicCaretPoint.x;
    }
    return x;
}
 
Example 11
Source File: AddCaretSelectNextAction.java    From netbeans with Apache License 2.0 5 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)) {
            EditorFindSupport findSupport = EditorFindSupport.getInstance();
            HashMap<String, Object> props = new HashMap<>(findSupport.createDefaultFindProperties());
            String searchWord = target.getSelectedText();
            int n = searchWord.indexOf('\n');
            if (n >= 0) {
                searchWord = searchWord.substring(0, n);
            }
            props.put(EditorFindSupport.FIND_WHAT, searchWord);
            props.put(EditorFindSupport.ADD_MULTICARET, Boolean.TRUE);
            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);
            props.put(EditorFindSupport.ADD_MULTICARET, Boolean.FALSE);
            findSupport.putFindProperties(props);
        } else {
            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);
            }
        }
    }
}
 
Example 12
Source File: GspKit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    Caret caret = target.getCaret();
    BaseDocument doc = (BaseDocument)target.getDocument();
    int dotPos = caret.getDot();
    if (handleDeletion(doc, dotPos)) {
        return;
    }
    super.actionPerformed(evt, target);
}
 
Example 13
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()) {
        final BaseDocument doc = (BaseDocument) target.getDocument();
        final Indent indenter = Indent.get(doc);
        final class R implements Runnable {

            @Override
            public void run() {
                try {
                    Caret caret = target.getCaret();
                    int caretPosition = caret.getDot();
                    int eolOffset = Utilities.getRowEnd(target, caretPosition);
                    doc.insertString(eolOffset, SEMICOLON, null);
                    newLineProcessor.processNewLine(eolOffset, caret, indenter);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        indenter.lock();
        try {
            doc.runAtomicAsUser(new R());
        } finally {
            indenter.unlock();
        }
    }
}
 
Example 14
Source File: CaretUndoEdit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void restoreCaret() {
    JTextComponent c = EditorRegistry.findComponent(doc);
    if (c != null) {
        Caret caret = c.getCaret();
        if (caret instanceof EditorCaret) {
            try {
                restoreEditorCaret((EditorCaret) caret);
            } catch (BadLocationException ex) {
                // Ignore caret restoration
            }
        } else {
            restoreLegacyCaret(caret);
        }
    }
}
 
Example 15
Source File: XMLCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * No completion inside PI, CDATA, comment section.
 * True only inside PI or CDATA section, false otherwise.
 * @param target
 */
boolean noCompletion(XMLSyntaxSupport support, JTextComponent target) {
    if(target == null || target.getCaret() == null)
        return false;
    int offset = target.getCaret().getDot();
    if(offset < 0)
        return false;            
    //no completion inside CDATA or comment section
    try {
        return support.<Boolean>runWithSequence(offset, (TokenSequence ts) -> {
            Token<XMLTokenId> token = ts.token();
            if (token == null) {
                if (!ts.moveNext()) {
                    return false;
                }
                token = ts.token();
                if (token == null) {
                    return false;
                }
            }
            if (token.id() == XMLTokenId.CDATA_SECTION
                    || token.id() == XMLTokenId.BLOCK_COMMENT
                    || token.id() == XMLTokenId.PI_START
                    || token.id() == XMLTokenId.PI_END
                    || token.id() == XMLTokenId.PI_CONTENT
                    || token.id() == XMLTokenId.PI_TARGET) {
                return true;
            }
            return false;
        });
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    return false;
}
 
Example 16
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 17
Source File: JmePaletteUtilities.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static int insert(String s, JTextComponent target, Document doc) throws BadLocationException {

        int start = -1;

        try {

            //firstly, find selected text range:
            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);

            //then, replace selected text range with the inserted one:
            start = caret.getDot();
            doc.insertString(start, s, null);

        } catch (BadLocationException ble) {}

        return start;

    }
 
Example 18
Source File: EditorFindSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
FindReplaceResult findReplaceImpl(String replaceExp, 
            Map<String, Object> props, boolean oppositeDir, JTextComponent c) {
        incSearchReset();
        props = getValidFindProperties(props);
        boolean back = isBackSearch(props, oppositeDir);
        if (props.get(FIND_WHAT) == null || !(props.get(FIND_WHAT) instanceof String)) {
            return null;
        }
        String findWhat = (String) props.get(FIND_WHAT);
        if (c != null) {
            ComponentUtils.clearStatusText(c);
            Caret caret = c.getCaret();
            int dotPos = caret.getDot();
            if (findMatches(c.getSelectedText(), props)) {
                Object dp = props.get(FIND_BACKWARD_SEARCH);
                boolean direction = (dp != null) ? ((Boolean)dp).booleanValue() : false;

                if (dotPos == (oppositeDir ^ direction ? c.getSelectionEnd() : c.getSelectionStart())) {
                    dotPos += (oppositeDir ^ direction ? -1 : 1);
                }
                
                if (replaceExp != null) {
                    if (oppositeDir ^ direction) {
                        dotPos = c.getSelectionEnd();
                    } else {
                        dotPos = c.getSelectionStart();
                    }
                }
            }
            
            Boolean b = (Boolean)props.get(FIND_BLOCK_SEARCH);
            boolean blockSearch = (b != null && b.booleanValue());
            Position blockStartPos = (Position) props.get(FIND_BLOCK_SEARCH_START);
            int blockSearchStart = (blockStartPos != null) ? blockStartPos.getOffset() : -1;
            int blockSearchEnd = getBlockEndOffset();

            boolean backSearch = Boolean.TRUE.equals(props.get(FIND_BACKWARD_SEARCH));
            if (backSearch) {
                blockSearchEnd = dotPos;
                dotPos = 0;
            }
            try {
                FindReplaceResult result = findReplaceInBlock(replaceExp, c, dotPos, 
                        (blockSearch && blockSearchStart > -1) ? blockSearchStart : 0, 
                        (blockSearch && blockSearchEnd > 0) ? blockSearchEnd : backSearch ? blockSearchEnd : -1, 
                        props, oppositeDir);
                
                if (result != null && result.hasErrorMsg()) {
                    ComponentUtils.setStatusText(c, result.getErrorMsg());
                    c.getCaret().setDot(c.getCaret().getDot());
                    return null;
                }
                int[] blk = null; 
                if (result != null){
                    blk = result.getFoundPositions();
                }
                if (blk != null) {
                    if (Boolean.TRUE.equals(props.get(EditorFindSupport.ADD_MULTICARET))) {
                        addCaretSelectText(c, blk[0], blk[1], back);
                    } else {
                        selectText(c, blk[0], blk[1], back);
                    }
                    String msg = NbBundle.getMessage(EditorFindSupport.class, FOUND_LOCALE, findWhat, DocUtils.debugPosition(c.getDocument(), Integer.valueOf(blk[0])));
//                    String msg = exp + NbBundle.getMessage(EditorFindSupport.class, FOUND_LOCALE)
//                                 + ' ' + DocUtils.debugPosition(c.getDocument(), blk[0]);
                    if (blk[2] == 1) { // wrap was done
                        msg += "; "; // NOI18N
                        if (blockSearch && blockSearchEnd>0 && blockSearchStart >-1){
                            msg += back ? NbBundle.getMessage(EditorFindSupport.class, WRAP_BLOCK_END_LOCALE)
                                   : NbBundle.getMessage(EditorFindSupport.class, WRAP_BLOCK_START_LOCALE);
                        }else{
                            msg += back ? NbBundle.getMessage(EditorFindSupport.class, WRAP_END_LOCALE)
                                   : NbBundle.getMessage(EditorFindSupport.class, WRAP_START_LOCALE);
                        }
                        ComponentUtils.setStatusText(c, msg, IMPORTANCE_FIND_OR_REPLACE);
                        c.getToolkit().beep();
                    } else {
                        ComponentUtils.setStatusText(c, msg, IMPORTANCE_FIND_OR_REPLACE);
                    }
                    return result;
                } else { // not found
                    ComponentUtils.setStatusText(c, NbBundle.getMessage(
                                                    EditorFindSupport.class, NOT_FOUND_LOCALE, findWhat), IMPORTANCE_FIND_OR_REPLACE);
                    // issue 14189 - selection was not removed
                    c.getCaret().setDot(c.getCaret().getDot());
                    }
            } catch (BadLocationException e) {
                LOG.log(Level.WARNING, e.getMessage(), e);
            }
        }
        return null;
    }
 
Example 19
Source File: EditorFindSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
boolean replaceImpl(Map<String, Object> props, boolean oppositeDir, JTextComponent c) throws BadLocationException {
    props = getValidFindProperties(props);
    boolean back = Boolean.TRUE.equals(props.get(FIND_BACKWARD_SEARCH));
    if (oppositeDir) {
        back = !back;
    }
    boolean blockSearch = Boolean.TRUE.equals(props.get(FIND_BLOCK_SEARCH));
    Position blockSearchStartPos = (Position) props.get(FIND_BLOCK_SEARCH_START);
    int blockSearchStartOffset = (blockSearchStartPos != null) ? blockSearchStartPos.getOffset() : -1;

    if (c != null) {
        String s = (String)props.get(FIND_REPLACE_WITH);
        Caret caret = c.getCaret();
        if (caret.isSelectionVisible() && caret.getDot() != caret.getMark()){
            Object dp = props.get(FIND_BACKWARD_SEARCH);
            boolean direction = (dp != null) ? ((Boolean)dp).booleanValue() : false;
            int dotPos = (oppositeDir ^ direction ? c.getSelectionEnd() : c.getSelectionStart());
            c.setCaretPosition(dotPos);
        }
        
        FindReplaceResult result = findReplaceImpl(s, props, oppositeDir, c);
        if (result!=null){
            s  = result.getReplacedString();
        } else {
            return false;
        }

        Document doc = c.getDocument();
        int startOffset = c.getSelectionStart();
        int len = c.getSelectionEnd() - startOffset;
        DocUtils.atomicLock(doc);
        try {
            if (len > 0) {
                doc.remove(startOffset, len);
            }
            if (s != null && s.length() > 0) {
                try {
                    NavigationHistory.getEdits().markWaypoint(c, startOffset, false, true);
                } catch (BadLocationException e) {
                    LOG.log(Level.WARNING, "Can't add position to the history of edits.", e); //NOI18N
                }
                doc.insertString(startOffset, s, null);
                if (startOffset == blockSearchStartOffset) { // Replaced at begining of block
                    blockSearchStartPos = doc.createPosition(startOffset);
                    props.put(EditorFindSupport.FIND_BLOCK_SEARCH_START, blockSearchStartPos);
                }
            }
        } finally {
            DocUtils.atomicUnlock(doc);
            if (blockSearch){
                setBlockSearchHighlight(blockSearchStartOffset, getBlockEndOffset());
            }
        }
        
        // adjust caret pos after replace operation
        int adjustedCaretPos = (back || s == null) ? startOffset : startOffset + s.length();
        caret.setDot(adjustedCaretPos);
        
    }
    
    return true;
}
 
Example 20
Source File: Utilities.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * @see isSelectionShowing(Caret)
 * @param component non-null component.
 * @return if selection is showing for component's caret.
 */
public static boolean isSelectionShowing(JTextComponent component) {
    Caret caret = component.getCaret();
    return (caret != null) && isSelectionShowing(caret);
}