Esempio n. 1
0
  /**
   * Replaces the selection with the specified text.
   *
   * @param selectedText The replacement text for the selection
   */
  public void setSelectedText(String selectedText) {
    if (!editable) {
      throw new InternalError("Text component" + " read only");
    }

    document.beginCompoundEdit();

    try {
      if (rectSelect) {
        Element map = document.getDefaultRootElement();

        int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
        int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

        // Certain rectangles satisfy this condition...
        if (end < start) {
          int tmp = end;
          end = start;
          start = tmp;
        }

        int lastNewline = 0;
        int currNewline = 0;

        for (int i = selectionStartLine; i <= selectionEndLine; i++) {
          Element lineElement = map.getElement(i);
          int lineStart = lineElement.getStartOffset();
          int lineEnd = lineElement.getEndOffset() - 1;
          int rectStart = Math.min(lineEnd, lineStart + start);

          document.remove(rectStart, Math.min(lineEnd - rectStart, end - start));

          if (selectedText == null) continue;

          currNewline = selectedText.indexOf('\n', lastNewline);
          if (currNewline == -1) currNewline = selectedText.length();

          document.insertString(rectStart, selectedText.substring(lastNewline, currNewline), null);

          lastNewline = Math.min(selectedText.length(), currNewline + 1);
        }

        if (selectedText != null && currNewline != selectedText.length()) {
          int offset = map.getElement(selectionEndLine).getEndOffset() - 1;
          document.insertString(offset, "\n", null);
          document.insertString(offset + 1, selectedText.substring(currNewline + 1), null);
        }
      } else {
        document.remove(selectionStart, selectionEnd - selectionStart);
        if (selectedText != null) {
          document.insertString(selectionStart, selectedText, null);
        }
      }
    } catch (BadLocationException bl) {
      bl.printStackTrace();
      throw new InternalError("Cannot replace" + " selection");
    }
    // No matter what happends... stops us from leaving document
    // in a bad state
    finally {
      document.endCompoundEdit();
    }

    setCaretPosition(selectionEnd);
  }