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

The following examples show how to use javax.swing.text.Caret#getMark() . 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: BaseCaret.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: SelectCodeElementAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private void fire(Object c) {
  if (c instanceof JTextComponent) {
    JTextComponent tc = (JTextComponent) c;
    Caret caret = tc.getCaret();
    int d = caret.getDot();
    int m = caret.getMark();
    // LOGGER.info(() -> String.format("%s / %s", m, d));
    if (d != m && (dot != d || mark != m)) {
      Optional.ofNullable(tc.getSelectedText()).ifPresent(str -> {
        LOGGER.info(() -> str);
        // StringSelection data = new StringSelection(str);
        // Toolkit.getDefaultToolkit().getSystemClipboard().setContents(data, data);
        tc.copy();
      });
    }
    dot = d;
    mark = m;
  }
}
 
Example 4
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 5
Source File: DeleteAction.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/**
 * This method was copied from
 * DefaultEditorKit.DeleteNextCharAction.actionPerformed(ActionEvent).
 *
 * @param e
 */
public void deleteNextChar(ActionEvent e) {
  JTextComponent c = getTextComponent(e);
  boolean beep = true;

  if ((c != null) && (c.isEditable())) {
    try {
      javax.swing.text.Document doc = c.getDocument();
      Caret caret = c.getCaret();
      int dot = caret.getDot();
      int mark = caret.getMark();

      if (dot != mark) {
        doc.remove(Math.min(dot, mark), Math.abs(dot - mark));
        beep = false;
      }
      else if (dot < doc.getLength()) {
        doc.remove(dot, 1);
        beep = false;
      }
    }
    catch (BadLocationException bl) {
    }
  }

  if (beep) {
    Toolkit.getDefaultToolkit().beep();
  }
}
 
Example 6
Source File: TextFieldLinker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void keyPressed(KeyEvent e) {
	Caret caret = linked.field.getCaret();
	boolean sel = caret.getMark() != caret.getDot();
	switch (e.getKeyCode()) {
		case KeyEvent.VK_BACK_SPACE:
			if (!sel && state.isAfterSep(linked.index)) {
				state.removeSep(linked.index - 1);
				e.consume();
			}
			break;
		case KeyEvent.VK_CLEAR:
			clear();
			break;
		case KeyEvent.VK_DELETE:
			if (!sel && state.isBeforeSep(linked.index)) {
				state.removeSep(linked.index);
				e.consume();
			}
			break;
		case KeyEvent.VK_KP_LEFT:
		case KeyEvent.VK_LEFT:
			if (state.isAfterSep(linked.index)) {
				state.navigateFieldLeft(linked.index - 1);
			}
			break;
		case KeyEvent.VK_KP_RIGHT:
		case KeyEvent.VK_RIGHT:
			if (state.isBeforeSep(linked.index)) {
				state.navigateFieldRight(linked.index + 1);
			}
			break;
		default:
			return;
	}
	syncStateLater();
}
 
Example 7
Source File: EditorCaret.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
    * 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.
    */
   private boolean isDragPossible(MouseEvent e) {
Object src = e.getSource();
if (src instanceof JComponent) {
    JComponent comp = (JComponent) src;
           boolean possible =  (comp == null) ? false : (comp.getTransferHandler() != null);
           if (possible && comp instanceof JTextComponent) {
               JTextComponent c = (JTextComponent) comp;
               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;
   }
 
Example 8
Source File: BreadCrumbsScheduler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected SchedulerEvent createSchedulerEvent (SourceModificationEvent event) {
    final JTextComponent ce = currentEditor;
    final Caret caret = ce != null ? ce.getCaret() : null;
    final Source s = getSource();
    if (event.getModifiedSource() == s && caret != null) {
        return new CursorMovedSchedulerEvent(this, caret.getDot(), caret.getMark()) { };
    }
    return null;
}
 
Example 9
Source File: DocumentationScrollPane.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void copy() {
    Caret caret = view.getCaret();
    if (caret.getDot() != caret.getMark()) {
        view.copy();
    } else {
        editorComponent.copy();
    }
}
 
Example 10
Source File: CursorSensitiveScheduler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected SchedulerEvent createSchedulerEvent (SourceModificationEvent event) {
    final JTextComponent ce = currentEditor;
    final Caret caret = ce != null ? ce.getCaret() : null;
    final Source s = getSource();
    if (event.getModifiedSource() == s && caret != null) {
        return new CursorMovedSchedulerEvent(this, caret.getDot(), caret.getMark()) { };
    }
    return null;
}
 
Example 11
Source File: GlyphGutter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public @Override void mouseDragged(MouseEvent e) {
    EditorUI eui = editorUI;
    if (eui == null) {
        return;
    }
    JTextComponent component = eui.getComponent();
    BaseTextUI textUI = (BaseTextUI)component.getUI();
    AbstractDocument aDoc = (AbstractDocument)component.getDocument();
    aDoc.readLock();
    try {
        // The drag must be extended to a next line in order to perform any selection
        int lineStartOffset = textUI.getPosFromY(e.getY());
        boolean updateDragEndOffset = false;
        if (dragStartOffset == -1) { // Drag starts now
            dragStartOffset = lineStartOffset;
            dragEndOffset = lineStartOffset;
        } else if (dragStartOffset == dragEndOffset) {
            if (lineStartOffset != dragStartOffset) {
                updateDragEndOffset = true;
            }
        } else {
            updateDragEndOffset = true;
        }
        if (updateDragEndOffset) {
            // Extend selection to active line's end or begining depending on dragStartOffset
            Caret caret = component.getCaret();
            if (lineStartOffset >= dragStartOffset) {
                if (caret.getMark() != dragStartOffset) {
                    caret.setDot(dragStartOffset);
                }
                // Check if the sele
                // Extend to next line's begining
                dragEndOffset = Math.min(Utilities.getRowEnd((BaseDocument) aDoc, lineStartOffset) + 1, aDoc.getLength());
            } else { // Backward selection
                // Check if the selection is already reverted i.e. it starts at dragStartOffset's line end
                if (caret.getMark() == dragStartOffset) {
                    caret.setDot(Utilities.getRowEnd((BaseDocument)aDoc, dragStartOffset) + 1);
                }
                dragEndOffset = lineStartOffset;
            }
            component.moveCaretPosition(dragEndOffset);
        }
    } catch (BadLocationException ble) {
        // Ignore rather than notify
    } finally {
        aDoc.readUnlock();
    }
}
 
Example 12
Source File: BaseAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Update the component according to the given update mask
* @param target target component to be updated.
* @param updateMask mask that specifies what will be updated
*/
public void updateComponent(JTextComponent target, int updateMask) {
    if (target != null && target.getDocument() instanceof BaseDocument) {
        BaseDocument doc = (BaseDocument)target.getDocument();
        boolean writeLocked = false;

        try {
            // remove selected text
            if ((updateMask & SELECTION_REMOVE) != 0) {
                writeLocked = true;
                doc.extWriteLock();
                Caret caret = target.getCaret();
                if (caret != null && Utilities.isSelectionShowing(caret)) {
                    int dot = caret.getDot();
                    int markPos = caret.getMark();
                    if (dot < markPos) { // swap positions
                        int tmpPos = dot;
                        dot = markPos;
                        markPos = tmpPos;
                    }
                    try {
                        target.getDocument().remove(markPos, dot - markPos);
                    } catch (BadLocationException e) {
                        Utilities.annotateLoggable(e);
                    }
                }
            }

            // reset magic caret position
            if ((updateMask & MAGIC_POSITION_RESET) != 0) {
                if (target.getCaret() != null)
                    target.getCaret().setMagicCaretPosition(null);
            }

            // reset merging of undoable edits
            if ((updateMask & UNDO_MERGE_RESET) != 0) {
                doc.resetUndoMerge();
            }

            // reset word matching
            if ((updateMask & WORD_MATCH_RESET) != 0) {
                ((BaseTextUI)target.getUI()).getEditorUI().getWordMatch().clear();
            }

            // Clear status bar text
            if (!recording && (updateMask & CLEAR_STATUS_TEXT) != 0) {
                Utilities.clearStatusText(target);
            }

            // Save current caret position in the jump-list
            if ((updateMask & SAVE_POSITION) != 0) {
                JumpList.checkAddEntry(target);
            }

        } finally {
            if (writeLocked) {
                doc.extWriteUnlock();
            }
        }
    }
}
 
Example 13
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 14
Source File: MasterMatcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void navigateAreas(
    int [] origin, 
    int [] matches,
    int caretOffset,
    Object caretBias,
    Caret caret,
    boolean select
) {
    if (matches != null && matches.length >= 2) {
        int newDotBackwardIdx = -1;
        int newDotForwardIdx = -1;
        
        for(int i = 0; i < matches.length / 2; i++) {
            if (matches[i * 2] <= origin[0] && 
                (newDotBackwardIdx == -1 || matches[i * 2] > matches[newDotBackwardIdx * 2])
            ) {
                newDotBackwardIdx = i;
            }
            
            if (matches[i * 2] >= origin[1] && 
                (newDotForwardIdx == -1 || matches[i * 2] < matches[newDotForwardIdx * 2])
            ) {
                newDotForwardIdx = i;
            }
        }
        
        if (newDotBackwardIdx != -1) {
            if (select) {
                int set, move;
                
                if (caretOffset < origin[1]) {
                    set = origin[0];
                    move = matches[2 * newDotBackwardIdx + 1];
                } else {
                    set = origin[1];
                    move = matches[2 * newDotBackwardIdx];
                }

                if (caret.getDot() == caret.getMark()) { // || (move <= caret.getMark() && caret.getMark() <= set)
                    caret.setDot(set);
                }
                caret.moveDot(move);
            } else {
                if (B_BACKWARD.equalsIgnoreCase(caretBias.toString())) {
                    caret.setDot(matches[2 * newDotBackwardIdx + 1]);
                } else {
                    caret.setDot(matches[2 * newDotBackwardIdx]);
                }
            }
        } else if (newDotForwardIdx != -1) {
            if (select) {
                int set, move;

                if (caretOffset > origin[0]) {
                    set = origin[1];
                    move = matches[2 * newDotForwardIdx];
                } else {
                    set = origin[0];
                    move = matches[2 * newDotForwardIdx + 1];
                }
                
                if (caret.getDot() == caret.getMark()) { //  || (set <= caret.getMark() && caret.getMark() <= move)
                    caret.setDot(set);
                }
                caret.moveDot(move);
            } else {
                if (B_BACKWARD.equalsIgnoreCase(caretBias.toString())) {
                    caret.setDot(matches[2 * newDotForwardIdx + 1]);
                } else {
                    caret.setDot(matches[2 * newDotForwardIdx]);
                }
            }
        }
    }
}
 
Example 15
Source File: Utilities.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Check whether caret's selection is visible and there is at least
 * one selected character showing.
 * 
 * @param caret non-null caret.
 * @return true if selection is visible and there is at least one selected character.
 */
public static boolean isSelectionShowing(Caret caret) {
    return caret.isSelectionVisible() && caret.getDot() != caret.getMark();
}