Example usage for javax.swing.text Document remove

List of usage examples for javax.swing.text Document remove

Introduction

In this page you can find the example usage for javax.swing.text Document remove.

Prototype

public void remove(int offs, int len) throws BadLocationException;

Source Link

Document

Removes a portion of the content of the document.

Usage

From source file:ch.zhaw.iamp.rct.ui.GrammarWindow.java

private void removeTabIfPossilbe(KeyEvent event, JTextComponent component) {
    try {/*www  .j  av a2 s.  c om*/
        Document doc = component.getDocument();
        int caretPostion = component.getCaretPosition();
        int lineStartIndex = doc.getText(0, caretPostion).lastIndexOf('\n') + 1;
        lineStartIndex = lineStartIndex < 0 ? 0 : lineStartIndex;
        lineStartIndex = lineStartIndex >= doc.getLength() ? doc.getLength() - 1 : lineStartIndex;
        int scanEndIndex = lineStartIndex + 4 <= doc.getLength() ? lineStartIndex + 4 : doc.getLength();

        for (int i = 0; i < 4 && i + lineStartIndex < scanEndIndex; i++) {
            if (doc.getText(lineStartIndex, 1).matches(" ")) {
                doc.remove(lineStartIndex, 1);
            } else if (doc.getText(lineStartIndex, 1).matches("\t")) {
                doc.remove(lineStartIndex, 1);
                break;
            } else {
                break;
            }
        }

        event.consume();
    } catch (BadLocationException ex) {
        System.out.println("Could not insert a tab: " + ex.getMessage());
    }
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method for finding (and optionally replacing) a string in the text
 *///from ww  w  . j a v  a  2  s  .  c om
private int findText(String findTerm, String replaceTerm, boolean bCaseSenstive, int iOffset) {
    JTextComponent jtpFindSource;
    if (sourceWindowActive || jtpSource.hasFocus()) {
        jtpFindSource = (JTextComponent) jtpSource;
    } else {
        jtpFindSource = (JTextComponent) jtpMain;
    }
    int searchPlace = -1;
    try {
        Document baseDocument = jtpFindSource.getDocument();
        searchPlace = (bCaseSenstive
                ? baseDocument.getText(0, baseDocument.getLength()).indexOf(findTerm, iOffset)
                : baseDocument.getText(0, baseDocument.getLength()).toLowerCase()
                        .indexOf(findTerm.toLowerCase(), iOffset));
        if (searchPlace > -1) {
            if (replaceTerm != null) {
                AttributeSet attribs = null;
                if (baseDocument instanceof HTMLDocument) {
                    Element element = ((HTMLDocument) baseDocument).getCharacterElement(searchPlace);
                    attribs = element.getAttributes();
                }
                baseDocument.remove(searchPlace, findTerm.length());
                baseDocument.insertString(searchPlace, replaceTerm, attribs);
                jtpFindSource.setCaretPosition(searchPlace + replaceTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + replaceTerm.length());
            } else {
                jtpFindSource.setCaretPosition(searchPlace + findTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + findTerm.length());
            }
        }
    } catch (BadLocationException ble) {
        logException("BadLocationException in actionPerformed method", ble);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
    }
    return searchPlace;
}

From source file:org.domainmath.gui.MainFrame.java

public void deleteText() {
    RSyntaxTextArea textArea = commandArea;
    boolean beep = true;
    if ((textArea != null) && (textArea.isEditable())) {
        try {/*from  w  w  w.j a  v  a2 s . c  o  m*/
            Document doc = textArea.getDocument();
            Caret caret = textArea.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()) {
                int delChars = 1;
                if (dot < doc.getLength() - 1) {
                    String dotChars = doc.getText(dot, 2);
                    char c0 = dotChars.charAt(0);
                    char c1 = dotChars.charAt(1);
                    if (c0 >= '\uD800' && c0 <= '\uDBFF' && c1 >= '\uDC00' && c1 <= '\uDFFF') {
                        delChars = 2;
                    }
                }
                doc.remove(dot, delChars);
                beep = false;
            }
        } catch (Exception bl) {
        }
    }

    if (beep) {
        UIManager.getLookAndFeel().provideErrorFeedback(textArea);
    }

    textArea.requestFocusInWindow();
}

From source file:org.executequery.gui.editor.autocomplete.QueryEditorAutoCompletePopupProvider.java

public void popupSelectionMade() {

    AutoCompleteListItem selectedListItem = (AutoCompleteListItem) autoCompletePopup.getSelectedItem();

    if (selectedListItem == null || selectedListItem.isNothingProposed()) {

        return;/*from  w ww .  j a  v  a 2  s  .  c  o  m*/
    }

    String selectedValue = selectedListItem.getInsertionValue();

    try {

        JTextComponent textComponent = queryEditorTextComponent();
        Document document = textComponent.getDocument();

        int caretPosition = textComponent.getCaretPosition();
        String wordAtCursor = queryEditor.getWordToCursor();

        if (StringUtils.isNotBlank(wordAtCursor)) {

            int wordAtCursorLength = wordAtCursor.length();
            int insertionIndex = caretPosition - wordAtCursorLength;

            if (selectedListItem.isKeyword() && isAllLowerCase(wordAtCursor)) {

                selectedValue = selectedValue.toLowerCase();
            }

            if (!Character.isLetterOrDigit(wordAtCursor.charAt(0))) {

                // cases where you might have a.column_name or similar

                insertionIndex++;
                wordAtCursorLength--;

            } else if (wordAtCursor.contains(".")) {

                int index = wordAtCursor.indexOf(".");
                insertionIndex += index + 1;
                wordAtCursorLength -= index + 1;
            }

            document.remove(insertionIndex, wordAtCursorLength);
            document.insertString(insertionIndex, selectedValue, null);

        } else {

            document.insertString(caretPosition, selectedValue, null);
        }

    } catch (BadLocationException e) {

        debug("Error on autocomplete insertion", e);

    } finally {

        autoCompletePopup.hidePopup();
    }

}

From source file:org.executequery.gui.editor.QueryEditorTextPanel.java

private void removeCommentFromRows(int startRow, int endRow) throws BadLocationException {

    Document document = queryPane.getDocument();

    Matcher matcher = sqlCommentMatcher();

    for (int i = startRow; i <= endRow; i++) {

        String text = queryPane.getTextAtRow(i);

        matcher.reset(text);/*from  ww  w  . j a  v a2  s .  co  m*/

        if (matcher.find()) {

            // retrieve the exact index of '--' since
            // matcher will return first whitespace

            int index = text.indexOf(SQL_COMMENT);
            int startOffset = queryPane.getRowPosition(i);

            document.remove(startOffset + index, 2);
        }

    }

}

From source file:org.languagetool.gui.LanguageToolSupport.java

private void applySuggestion(String str, int start, int end) {
    if (end < start) {
        throw new IllegalArgumentException("end before start: " + end + " < " + start);
    }//  www.  j a va 2s.co  m
    Document doc = this.textComponent.getDocument();
    if (doc != null) {
        try {
            if (this.undo != null) {
                this.undo.startCompoundEdit();
            }
            if (doc instanceof AbstractDocument) {
                ((AbstractDocument) doc).replace(start, end - start, str, null);
            } else {
                doc.remove(start, end - start);
                doc.insertString(start, str, null);
            }
        } catch (BadLocationException e) {
            throw new IllegalArgumentException(e);
        } finally {
            if (this.undo != null) {
                this.undo.endCompoundEdit();
            }
        }
    }
}

From source file:processing.app.EditorTab.java

/**
 * Replace the entire contents of this tab.
 *///from   w  w w . ja v  a 2  s.  co m
public void setText(String what) {
    // Remove all highlights, since these will all end up at the start of the
    // text otherwise. Preserving them is tricky, so better just remove them.
    textarea.removeAllLineHighlights();
    // Set the caret update policy to NEVER_UPDATE while completely replacing
    // the current text. Normally, the caret tracks inserts and deletions, but
    // replacing the entire text will always make the caret end up at the end,
    // which isn't really useful. With NEVER_UPDATE, the caret will just keep
    // its absolute position (number of characters from the start), which isn't
    // always perfect, but the best we can do without making a diff of the old
    // and new text and some guesswork.
    // Note that we cannot use textarea.setText() here, since that first removes
    // text and then inserts the new text. Even with NEVER_UPDATE, the caret
    // always makes sure to stay valid, so first removing all text makes it
    // reset to 0. Also note that simply saving and restoring the caret position
    // will work, but then the scroll position might change in response to the
    // caret position.
    DefaultCaret caret = (DefaultCaret) textarea.getCaret();
    int policy = caret.getUpdatePolicy();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    try {
        Document doc = textarea.getDocument();
        int oldLength = doc.getLength();
        // The undo manager already seems to group the insert and remove together
        // automatically, but better be explicit about it.
        textarea.beginAtomicEdit();
        try {
            doc.insertString(oldLength, what, null);
            doc.remove(0, oldLength);
        } catch (BadLocationException e) {
            System.err.println("Unexpected failure replacing text");
        } finally {
            textarea.endAtomicEdit();
        }
    } finally {
        caret.setUpdatePolicy(policy);
    }
}

From source file:tk.tomby.tedit.core.snr.FindReplaceWorker.java

/**
 * DOCUMENT ME!/*from   www.  j a  va 2  s  .  c o  m*/
 */
public void replace() {
    String replace = PreferenceManager.getString("snr.replace", "");

    if ((replace != null) && !replace.equals("")) {
        int start = buffer.getSelectionStart();
        int end = buffer.getSelectionEnd();

        if (start != end) {
            Document doc = buffer.getDocument();

            try {
                doc.remove(start, end - start);
                doc.insertString(start, replace, null);
            } catch (BadLocationException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}