javax.swing.text.Caret Java Examples

The following examples show how to use javax.swing.text.Caret. 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: MacEditorKit.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * The operation to perform when this action is triggered.
 *
 * @param e DOCUMENT ME!
 */
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);

    if (target != null) {

        // target.getUI().getNextVisualPositionFrom(t
        Caret caret = target.getCaret();
        int   dot   = caret.getDot();

        verticalAction.actionPerformed(e);

        if (dot == caret.getDot()) {
            Point magic = caret.getMagicCaretPosition();

            beginEndAction.actionPerformed(e);
            caret.setMagicCaretPosition(magic);
        }
    }
}
 
Example #2
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) {
        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();
        }
    }
}
 
Example #3
Source File: PHPActionTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void testInFile(String file, String actionName) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

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

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

    runKitAction(ta, actionName, null);

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

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, goldenFileExtension());
}
 
Example #4
Source File: 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 #5
Source File: EntityClass.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public boolean handleTransfer(JTextComponent targetComponent) {
    try {
        jsfLibrariesSupport = PaletteUtils.getJsfLibrariesSupport(targetComponent);
        if (jsfLibrariesSupport == null) {
            return false;
        }
        Caret caret = targetComponent.getCaret();
        int position0 = Math.min(caret.getDot(), caret.getMark());
        int position1 = Math.max(caret.getDot(), caret.getMark());
        int len = targetComponent.getDocument().getLength() - position1;
        boolean containsFView = targetComponent.getText(0, position0).contains("<f:view>")
                && targetComponent.getText(position1, len).contains("</f:view>");
        String body = createBody(targetComponent, !containsFView);
        JSFPaletteUtilities.insert(body, targetComponent);
        jsfLibrariesSupport.importLibraries(DefaultLibraryInfo.HTML, DefaultLibraryInfo.JSF_CORE);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
        return false;
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
        return false;
    }

    return true;
}
 
Example #6
Source File: TransposeLettersAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        final Document doc = target.getDocument();
        DocUtils.runAtomicAsUser(doc, new Runnable() {
            @Override
            public void run() {
                Caret caret = target.getCaret();
                if(caret instanceof EditorCaret) {
                    EditorCaret editorCaret = (EditorCaret) caret;
                    for (CaretInfo caretInfo : editorCaret.getSortedCarets()) {
                        if (!DocUtils.transposeLetters(doc, caretInfo.getDot())) {
                            // Cannot transpose (at end of doc) => beep
                            target.getToolkit().beep();
                        }
                    }
                } else {
                    if (!DocUtils.transposeLetters(doc, target.getCaretPosition())) {
                        // Cannot transpose (at end of doc) => beep
                        target.getToolkit().beep();
                    }
                }
            }
        });
    }
}
 
Example #7
Source File: JSFPaletteUtilities.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 #8
Source File: I18nManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Highlights found hasrdcoded string. */
private void highlightHCString() {
    HardCodedString hStr = hcString;
    
    if (hStr == null) {
        return;
    }
    
    // Highlight found hard coded string.
    Caret caret = caretWRef.get();
    
    if (caret != null) {
        caret.setDot(hStr.getStartPosition().getOffset());
        caret.moveDot(hStr.getEndPosition().getOffset());
    }
}
 
Example #9
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #10
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 #11
Source File: BracesMatchHighlighting.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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
        );
    }
}
 
Example #12
Source File: MulticaretHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private MulticaretHandler(final JTextComponent c) {
    this.doc = c.getDocument();
    doc.render(() -> {
        Caret caret = c.getCaret();
        if (caret instanceof EditorCaret) {
            List<CaretInfo> carets = ((EditorCaret) caret).getCarets();
            if (carets.size() > 1) {
                this.regions = new ArrayList<>(carets.size());
                carets.forEach((ci) -> {
                    try {
                        int[] block = ci.isSelectionShowing() ? null : Utilities.getIdentifierBlock(c, ci.getDot());
                        Position start = NbDocument.createPosition(doc, block != null ? block[0] : ci.getSelectionStart(), Position.Bias.Backward);
                        Position end = NbDocument.createPosition(doc, block != null ? block[1] : ci.getSelectionEnd(), Position.Bias.Forward);
                        regions.add(new MutablePositionRegion(start, end));
                    } catch (BadLocationException ex) {}
                });
                Collections.reverse(regions);
            }
        }
    });
}
 
Example #13
Source File: CslEditorKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
                }
            }
        }
    }
}
 
Example #14
Source File: Abbrev.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Expand abbreviation on current caret position.
* Remove characters back to the word start and insert expanded abbreviation.
* @return whether the typed character should be added to the abbreviation or not
*/
public boolean expandString(final String expandStr, final ActionEvent evt)
throws BadLocationException {
    // Disabled due to code templates
    if (true) {
        reset();
        return true;
    }

    final BaseDocument doc = editorUI.getDocument();
    final Object[] result = new Object [1];
    doc.runAtomicAsUser (new Runnable () {
        public void run () {
            try {
                Caret caret = editorUI.getComponent().getCaret();
                int pos = caret.getDot() - expandStr.length();
                try {
                    doc.remove(pos, expandStr.length());
                    result [0] = doExpansion(pos, expandStr, evt);
                } catch (BadLocationException ex) {
                    result [0] = ex;
                }
            } finally {
                if (result [0] instanceof Boolean && (Boolean) result [0]) {
                    reset();
                } else {
                    doc.breakAtomicLock();
                }
            }
        }
    });
    if (result [0] instanceof BadLocationException)
        throw (BadLocationException) result [0];
    return (Boolean) result [0];
}
 
Example #15
Source File: CommentsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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
}
 
Example #16
Source File: Test6462562.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

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

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

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

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example #17
Source File: I18nManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Initializes caret. */
private void initCaret(EditorCookie ec) {
    JEditorPane[] panes = ec.getOpenedPanes();
    if (panes == null) {
        NotifyDescriptor.Message message = new NotifyDescriptor.Message(
                I18nUtil.getBundle().getString("MSG_CouldNotOpen"), //NOI18N
                NotifyDescriptor.ERROR_MESSAGE);
        DialogDisplayer.getDefault().notify(message);
        return;
    }

    // Keep only weak ref to caret, the strong one maintains editor pane itself.
    caretWRef = new WeakReference<Caret>(panes[0].getCaret());
}
 
Example #18
Source File: BrowserPane.java    From SwingBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initial settings
 */
protected void init()
{
    // "support for SSL"
    String handlerPkgs = System.getProperty("java.protocol.handler.pkgs");
    if ((handlerPkgs != null) && !(handlerPkgs.isEmpty())) {
        handlerPkgs = handlerPkgs + "|com.sun.net.ssl.internal.www.protocol";
    } else {
    	handlerPkgs = "com.sun.net.ssl.internal.www.protocol";
    }
    System.setProperty("java.protocol.handler.pkgs", handlerPkgs);

    java.security.Security
            .addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    // Create custom EditorKit if needed
    if (swingBoxEditorKit == null) {
        swingBoxEditorKit = new SwingBoxEditorKit();
    }

    setEditable(false);
    setContentType("text/html");

    activateTooltip(true);

    Caret caret = getCaret();
    if (caret instanceof DefaultCaret)
    	((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
 
Example #19
Source File: XMLKit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target == null) return;
    if (!target.isEditable() || !target.isEnabled()) {
        problem(null);
        return;
    }
    Caret caret = target.getCaret();
    BaseDocument doc = (BaseDocument)target.getDocument();
    try {
        doc.dump(System.out);    
        if (target == null)  throw new BadLocationException(null,0);  // folish compiler
    } catch (BadLocationException e) {
        problem(null);
    }
}
 
Example #20
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 #21
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 #22
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 #23
Source File: BracesMatchAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e, JTextComponent component) {
    Document document = component.getDocument();
    Caret caret = component.getCaret();
    
    MasterMatcher.get(component).navigate(
        document,
        caret.getDot(), 
        caret,
        select
    );
}
 
Example #24
Source File: Test6462562.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public boolean test(int pos, int selectionLength, String todo, Object expectedResult) {
    Object v0 = getValue();

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

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

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

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

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

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

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

    Object v1 = getValue();
    if (! v1.equals(expectedResult)) {
        System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n",
                v0, pos, pos + selectionLength, desc);
        System.err.printf("   Result: '%s', expected: '%s'\n", v1, expectedResult);
        failed = true;
        return false;
    }
    return true;
}
 
Example #26
Source File: GroovyTypedTextInterceptor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void reindent(BaseDocument doc, int offset, TokenId id, Caret caret)
    throws BadLocationException {
    TokenSequence<GroovyTokenId> ts = LexUtilities.getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        ts.move(offset);

        if (!ts.moveNext() && !ts.movePrevious()) {
            return;
        }

        Token<GroovyTokenId> token = ts.token();

        if ((token.id() == id)) {
            final int rowFirstNonWhite = Utilities.getRowFirstNonWhite(doc, offset);
            // Ensure that this token is at the beginning of the line
            if (ts.offset() > rowFirstNonWhite) {
                return;
            }

            OffsetRange begin = OffsetRange.NONE;

            if (id == GroovyTokenId.RBRACE) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACE, GroovyTokenId.RBRACE);
            } else if (id == GroovyTokenId.RBRACKET) {
                begin = LexUtilities.findBwd(doc, ts, GroovyTokenId.LBRACKET, GroovyTokenId.RBRACKET);
            }

            if (begin != OffsetRange.NONE) {
                int beginOffset = begin.getStart();
                int indent = GsfUtilities.getLineIndent(doc, beginOffset);
                previousAdjustmentIndent = GsfUtilities.getLineIndent(doc, offset);
                GsfUtilities.setLineIndentation(doc, offset, indent);
                previousAdjustmentOffset = caret.getDot();
            }
        }
    }
}
 
Example #27
Source File: BraceCompletionDeleteAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void charBackspaced (
    BaseDocument        document, 
    int                 offset, 
    Caret               caret, 
    char                character
) throws BadLocationException {
    TokenSequence tokenSequence = Utils.getTokenSequence (document, offset);
    if (tokenSequence != null) {
        String mimeType = tokenSequence.language ().mimeType ();
        try {
            Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
            List<Feature> completes = l.getFeatureList ().getFeatures ("COMPLETE");
            Iterator<Feature> it = completes.iterator ();
            while (it.hasNext ()) {
                Feature complete = it.next ();
                if (complete.getType () != Feature.Type.STRING)
                    continue;
                String s = (String) complete.getValue ();
                int i = s.indexOf (':');
                if (i != 1) continue;
                String ss = document.getText (
                    caret.getDot (), 
                    s.length () - i - 1
                );
                if (s.endsWith (ss) && 
                    s.charAt (0) == character
                ) {
                    document.remove (caret.getDot (), s.length () - i - 1);
                    return;
                }
            }
        } catch (LanguageDefinitionNotFoundException ex) {
            // ignore the exception
        }
    }
    super.charBackspaced (document, offset, caret, character);
}
 
Example #28
Source File: CslTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void assertAutoQuery(QueryType queryType, String source, String typedText) {
    CodeCompletionHandler completer = getCodeCompleter();
    int caretPos = source.indexOf('^');
    source = source.substring(0, caretPos) + source.substring(caretPos+1);

    BaseDocument doc = getDocument(source);
    JTextArea ta = new JTextArea(doc);
    Caret caret = ta.getCaret();
    caret.setDot(caretPos);

    QueryType qt = completer.getAutoQuery(ta, typedText);
    assertEquals(queryType, qt);
}
 
Example #29
Source File: CamelCaseActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void moveToNewOffset(JTextComponent target, int offset, int length) throws BadLocationException {
    Caret caret = target.getCaret();
    if (caret instanceof BaseCaret && RectangularSelectionUtils.isRectangularSelection(target)) {
        ((BaseCaret) caret).extendRectangularSelection(true, true);
    } else {
        target.getCaret().moveDot(offset + length);
    }
}
 
Example #30
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (!target.isEditable() || !target.isEnabled()) {
        target.getToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) target.getDocument();
    final Indent indenter = Indent.get(doc);
    final class R implements Runnable {
        public @Override void run() {
            try {
                Caret caret = target.getCaret();
                int dotpos = caret.getDot();
                int eoloffset = Utilities.getRowEnd(target, dotpos);
                doc.insertString(eoloffset, "" + what, null); //NOI18N
                if (withNewline) {
                    //This is code from the editor module, but it is
                    //a pretty strange way to do this:
                    doc.insertString(dotpos, "-", null); //NOI18N
                    doc.remove(dotpos, 1);
                    int eolDot = Utilities.getRowEnd(target, caret.getDot());
                    int newDotPos = indenter.indentNewLine(eolDot);
                    caret.setDot(newDotPos);
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    indenter.lock();
    try {
        doc.runAtomicAsUser(new R());
    } finally {
        indenter.unlock();
    }
}