Java Code Examples for javax.swing.text.StyledDocument#getLength()

The following examples show how to use javax.swing.text.StyledDocument#getLength() . 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: SwingLogPanel.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/** Removes any messages writtin in "red" style. */
public void clearError() {
    if (log == null)
        return;
    // Since this class always removes "red" messages prior to writing
    // anything,
    // that means if there are any red messages, they will always be at the
    // end of the JTextPane.
    StyledDocument doc = log.getStyledDocument();
    int n = doc.getLength();
    if (n > lastSize) {
        try {
            doc.remove(lastSize, n - lastSize);
        } catch (BadLocationException e) {}
    }
    if (batch.size() > 0) {
        for (String msg : batch) {
            reallyLog(msg, styleRegular);
        }
        batch.clear();
    }
}
 
Example 2
Source File: MWPaneSelectionManager.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Select last occurrence of text. 
 */
public void selectLastOccurrence() {
  StyledDocument doc = textPane.getStyledDocument();
  int lastStart = Integer.MIN_VALUE;
  for (int pos = doc.getLength(); pos > 0; pos = lastStart) {
    Element run = doc.getCharacterElement(pos - 1);
    lastStart = run.getStartOffset();
    MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
    if ((attr != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_OCCURRENCE) != Boolean.FALSE)) {
      select(run);
      return;
    }
  }
}
 
Example 3
Source File: SwingLogPanel.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
private void reallyLog(String text, Style style) {
    if (log == null || text.length() == 0)
        return;
    int i = text.lastIndexOf('\n'), j = text.lastIndexOf('\r');
    if (i >= 0 && i < j) {
        i = j;
    }
    StyledDocument doc = log.getStyledDocument();
    try {
        if (i < 0) {
            doc.insertString(doc.getLength(), text, style);
        } else {
            // Performs intelligent caret positioning
            doc.insertString(doc.getLength(), text.substring(0, i + 1), style);
            log.setCaretPosition(doc.getLength());
            if (i < text.length() - 1) {
                doc.insertString(doc.getLength(), text.substring(i + 1), style);
            }
        }
    } catch (BadLocationException e) {
        // Harmless
    }
    if (style != styleRed) {
        lastSize = doc.getLength();
    }
}
 
Example 4
Source File: IndentFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isEmpty (
    int                     ln,
    StyledDocument          document,
    Set<Integer>            whitespaces
) throws BadLocationException {
    int start = NbDocument.findLineOffset (document, ln);
    int end = document.getLength ();
    try {
        end = NbDocument.findLineOffset (document, ln + 1) - 1;
    } catch (IndexOutOfBoundsException ex) {
    }
    TokenSequence ts = Utils.getTokenSequence (document, start);
    if (ts.token () == null) return true;
    while (whitespaces.contains (ts.token ().id ().ordinal ())) {
        if (!ts.moveNext ()) return true;
        if (ts.offset () > end) return true;
    }
    return false;
}
 
Example 5
Source File: ComputeAnnotations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Position getPosition(final StyledDocument doc, final int offset) {
    class Impl implements Runnable {
        private Position pos;
        public void run() {
            if (offset < 0 || offset >= doc.getLength())
                return ;

            try {
                pos = doc.createPosition(offset - NbDocument.findLineColumn(doc, offset));
            } catch (BadLocationException ex) {
                //should not happen?
                Logger.getLogger(ComputeAnnotations.class.getName()).log(Level.FINE, null, ex);
            }
        }
    }

    Impl i = new Impl();

    doc.render(i);

    return i.pos;
}
 
Example 6
Source File: TaskDialog.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
private void updateErrorDocument(StyledDocument doc) {
	if (doc == null) {
		return;
	}
	int length = doc.getLength();
	for (UpdateTask task : updateTasks) {
		task.insertLog(doc);
	}
	if (doc.getLength() > length) { //If changed
		try {
			doc.insertString(length, Formater.columnDate(new Date()) + "\n\r", null);
			if (length > 0) {
				doc.insertString(length, "\n\r", null);
			}
		} catch (BadLocationException ex) {
			//Shouldn't be possible....
		}
	}
}
 
Example 7
Source File: TooltipWindow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public RevisionLinker (String revision, StyledDocument sd, File repository, File root) {
    this.revision = revision;
    this.repository = repository;
    this.root = root;
    int doclen = sd.getLength();
    int textlen = revision.length();

    docstart = doclen;
    docend = doclen + textlen;
}
 
Example 8
Source File: VCSHyperlinkSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private IssueLinker(VCSHyperlinkProvider hp, Style issueHyperlinkStyle, File root, StyledDocument sd, String text, int[] spans) {
    this.length = spans.length / 2;
    this.docstart = new int[length];
    this.docend = new int[length];
    this.start = new int[length];
    this.end = new int[length];
    this.hp = hp;
    this.root = root;
    this.text = text;
    this.issueHyperlinkStyle = issueHyperlinkStyle;

    for (int i = 0; i < spans.length;) {
        int linkeridx = i / 2;
        int spanstart = spans[i++];
        int spanend = spans[i++];
        if(spanend < spanstart) {
            LOG.warning("Hyperlink provider " + hp.getClass().getName() + " returns wrong spans [" + spanstart + "," + spanend + "]");
            continue;
        }

        int doclen = sd.getLength();
        this.start[linkeridx] = spanstart;
        this.end[linkeridx] = spanend;
        this.docstart[linkeridx] = doclen + spanstart;
        this.docend[linkeridx] = doclen + spanend;
    }
}
 
Example 9
Source File: VCSHyperlinkSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public AuthorLinker(KenaiUser kenaiUser, Style authorStyle, StyledDocument sd, String author, String insertToChat) throws BadLocationException {
    this.kenaiUser = kenaiUser;
    this.author = author;
    this.authorStyle = authorStyle;
    this.insertToChat = insertToChat;

    int doclen = sd.getLength();
    int textlen = author.length();

    docstart = doclen;
    docend = doclen + textlen;
}
 
Example 10
Source File: TextEditorGUI.java    From trygve with GNU General Public License v2.0 5 votes vote down vote up
public void removeAllBreakpoints() {
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final SimpleAttributeSet sas = new SimpleAttributeSet();
	StyleConstants.setBackground(sas, new java.awt.Color(233, 228, 242));
	
	// https://stackoverflow.com/questions/28927274/get-attributes-of-selected-text-in-jtextpane
	for(int i = 0; i < doc.getLength(); i++) {
	    final AttributeSet set = doc.getCharacterElement(i).getAttributes();
	    final Color backgroundColor = StyleConstants.getBackground(set);
	    if (backgroundColor.equals(Color.cyan)) {
	    	// The breakpoint color. Remove breakpoint annotation from this text
	    	doc.setCharacterAttributes(i, 1, sas, false);
	    }
	}
}
 
Example 11
Source File: EuropePanel.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add text to the transaction log.
 *
 * @param text The text to add.
 */
private void add(String text) {
    StyledDocument doc = getStyledDocument();
    try {
        if (doc.getLength() > 0) text = "\n\n" + text;
        doc.insertString(doc.getLength(), text, null);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Transaction log update failure", e);
    }
}
 
Example 12
Source File: TextEditorGUI.java    From trygve with GNU General Public License v2.0 5 votes vote down vote up
public void setBreakpointToEOLAt(int byteOffset, int lineNumber) {
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final Element paragraphElement = doc.getParagraphElement(byteOffset);
	if (paragraphElement.getClass() == BranchElement.class) {
		final SimpleAttributeSet sas = new SimpleAttributeSet(); 
		StyleConstants.setBackground(sas, Color.cyan);
		
		// Look for ending delimiter
		int length = 1;
		try {
			for (int i = byteOffset; ; i++) {
				if (i >= doc.getLength()) {
					length = i - byteOffset + 1;
					break;
				} else if (doc.getText(i, 1).equals("\n")) {
					length = i - byteOffset;
					break;
				}
			}
		} catch (BadLocationException ble) {
			length = 0;
		}
		if (0 < length) {
			doc.setCharacterAttributes(byteOffset, length, sas, false);
		}
	}
}
 
Example 13
Source File: OurConsole.java    From org.alloytools.alloy with Apache License 2.0 4 votes vote down vote up
/** This method processes a user command. */
private void do_command(Computer computer, String cmd) {
    cmd = cmd.trim();
    if (cmd.length() == 0)
        return;

    cmd = TableView.revertSuffix(cmd);
    StyledDocument doc = main.getStyledDocument();
    if (history.size() >= 2 && cmd.equals(history.get(history.size() - 2))) {
        // If the user merely repeated the most recent command, then don't
        // grow the history
        history.set(history.size() - 1, "");
    } else {
        // Otherwise, grow the history
        history.set(history.size() - 1, cmd);
        history.add("");
    }
    browse = history.size() - 1;
    // display the command
    int old = doc.getLength();
    do_add(len, cmd + "\n\n", plain);
    len += (doc.getLength() - old);
    // perform the computation
    boolean isBad = false;
    Object result;
    try {
        result = computer.compute(cmd);
    } catch (Throwable ex) {
        result = ex.toString();
        isBad = true;
    }
    int savePosition = len;
    // display the outcome
    old = doc.getLength();
    do_add(len, result.toString().trim() + "\n\n", (isBad ? bad : good));
    len += (doc.getLength() - old);
    // indent the outcome
    main.setSelectionStart(savePosition + 1);
    main.setSelectionEnd(len);
    main.setParagraphAttributes(good, false);
    // redraw then scroll to the bottom
    invalidate();
    repaint();
    validate();
    sub.scrollRectToVisible(new Rectangle(0, sub.getY(), 1, sub.getHeight()));
    do_pagedown(); // need to do this after the validate() so that the
                  // scrollbar knows the new limit
}
 
Example 14
Source File: MWPaneReplaceAllAction.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * @param e Event.
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
@Override
public void actionPerformed(ActionEvent e) {
  MWPane textPane = getMWPane(e);
  if (textPane == null) {
    return;
  }
  StyledDocument doc = textPane.getStyledDocument();
  if (doc == null) {
    return;
  }
  int length = doc.getLength();
  int lastEnd = Integer.MAX_VALUE;
  for (int pos = 0; pos < length; pos = lastEnd) {
    try {
      Element run = doc.getCharacterElement(pos);
      lastEnd = run.getEndOffset();
      if (pos == lastEnd) {
        // offset + length beyond length of document, bail.
        break;
      }
      MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
      if ((attr != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO) != null)) {
        Object attrInfo = attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO);
        if (attrInfo instanceof CheckErrorResult) {
          int startOffset = MWPaneFormatter.getUUIDStartOffset(textPane, run);
          int endOffset = MWPaneFormatter.getUUIDEndOffet(textPane, run);
          if (originalText.equals(textPane.getText(startOffset, endOffset - startOffset))) {
            boolean possible = false;
            CheckErrorResult info = (CheckErrorResult) attrInfo;
            List<Actionnable> actionnables = info.getPossibleActions();
            if (actionnables != null) {
              for (Actionnable actionnable : actionnables) {
                possible |= actionnable.isPossibleReplacement(newText);
              }
            }
            if (possible) {
              doc.remove(startOffset, endOffset - startOffset);
              doc.insertString(startOffset, newText, attr);
              lastEnd = startOffset + newText.length();
            }
          }
        }
      }
    } catch (BadLocationException exception) {
      // Nothing to do
    }
  }
}
 
Example 15
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Get a list of MIME types of languages found on a line.
 * @param line The line to search for the MIME types.
 * @return A set of MIME types.
 * @since 2.50
 */
public Set<String> getMIMETypesOnLine(Line line) {
    EditorCookie editorCookie = line.getLookup().lookup(EditorCookie.class);
    if (editorCookie == null) {
        DataObject dobj = line.getLookup().lookup(DataObject.class);
        if (dobj != null) {
            editorCookie = dobj.getLookup().lookup(EditorCookie.class);
        }
        if (editorCookie == null) {
            return Collections.emptySet();
        }
    }
    StyledDocument document = editorCookie.getDocument();
    if (document == null) {
        return Collections.emptySet();
    }
    Set<String> mimeTypes = null;
    ((AbstractDocument) document).readLock();
    try {
        TokenHierarchy<Document> th = TokenHierarchy.get((Document) document);
        int ln = line.getLineNumber();
        int offset = NbDocument.findLineOffset(document, ln);
        int maxOffset = document.getLength() - 1;
        int maxLine = NbDocument.findLineNumber(document, maxOffset);
        int offset2;
        if (ln + 1 > maxLine) {
            offset2 = maxOffset;
        } else {
            offset2 = NbDocument.findLineOffset(document, ln+1) - 1;
        }
        // The line has offsets <offset, offset2>
        Set<LanguagePath> languagePaths = th.languagePaths();
        for (LanguagePath lp : languagePaths) {
            List<TokenSequence<?>> tsl = th.tokenSequenceList(lp, offset, offset2);
            for (TokenSequence ts : tsl) {
                if (ts.moveNext()) {
                    //int to = ts.offset();
                    //if (!(offset <= to && to < offset2)) {
                    //    continue;
                    //}
                    String mimeType = ts.language().mimeType();
                    if (mimeType != null) {
                        if (mimeTypes == null) {
                            mimeTypes = Collections.singleton(mimeType);
                        } else {
                            if (mimeTypes.size() == 1) {
                                mimeTypes = new HashSet<String>(mimeTypes);
                            }
                            mimeTypes.add(mimeType);
                        }
                    }
                }
            }
        }
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    return (mimeTypes != null) ? mimeTypes : Collections.<String>emptySet();
    
}
 
Example 16
Source File: PositionBounds.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Replaces the text contained in this range.
* This replacement is done atomically, and so is preferable to manual inserts & removes.
* <p>If you are running this from user-oriented code, you may want to wrap it in {@link NbDocument#runAtomicAsUser}.
* @param text new text to insert over existing text
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public void setText(final String text) throws BadLocationException  {
    final StyledDocument doc = guards.getDocument();
    final BadLocationException[] hold = new BadLocationException[] { null };
    Runnable run = new Runnable() {
            public void run() {
                try {
                    int p1 = begin.getOffset();
                    int p2 = end.getOffset();
                    int len = text.length();

                    if (len == 0) { // 1) set empty string

                        if (p2 > p1) {
                            doc.remove(p1, p2 - p1);
                        }
                    } else { // 2) set non empty string

                        int docLen = doc.getLength();

                        if ((p2 - p1) >= 1) {
                            doc.insertString(p1 + 1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;
                            doc.remove(p1 + 1 + len, p2 - p1 - 1);
                            doc.remove(p1, 1);
                        } else {
                            // zero or exactly one character:
                            // adjust the positions if they are
                            // biased to not absorb the text inserted at the start/end
                            // it would be ridiculous not to have text set by setText
                            // be part of the bounds.
                            doc.insertString(p1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;

                            if (p2 > p1) {
                                doc.remove(p1 + len, p2 - p1);
                            }

                            if (begin.getOffset() != p1) {
                                begin = doc.createPosition(p1);
                            }

                            if ((end.getOffset() - p1) != len) {
                                end = doc.createPosition(p1 + len);
                            }
                            assertPositionBounds();
                        }
                    }
                } catch (BadLocationException e) {
                    hold[0] = e;
                }
            }
        };

    GuardedSectionsImpl.doRunAtomic(doc, run);

    if (hold[0] != null) {
        throw hold[0];
    }
}
 
Example 17
Source File: AddModulePanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void showDescription() {
    StyledDocument doc = descValue.getStyledDocument();
    final Boolean matchCase = matchCaseValue.isSelected();
    try {
        doc.remove(0, doc.getLength());
        ModuleDependency[] deps = getSelectedDependencies();
        if (deps.length != 1) {
            return;
        }
        String longDesc = deps[0].getModuleEntry().getLongDescription();
        if (longDesc != null) {
            doc.insertString(0, longDesc, null);
        }
        String filterText = filterValue.getText().trim();
        if (filterText.length() != 0 && !FILTER_DESCRIPTION.equals(filterText)) {
            doc.insertString(doc.getLength(), "\n\n", null); // NOI18N
            Style bold = doc.addStyle(null, null);
            bold.addAttribute(StyleConstants.Bold, Boolean.TRUE);
            doc.insertString(doc.getLength(), getMessage("TEXT_matching_filter_contents"), bold);
            doc.insertString(doc.getLength(), "\n", null); // NOI18N
            if (filterText.length() > 0) {
                String filterTextLC = matchCase?filterText:filterText.toLowerCase(Locale.US);
                Style match = doc.addStyle(null, null);
                match.addAttribute(StyleConstants.Background, UIManager.get("selection.highlight")!=null?
                        UIManager.get("selection.highlight"):new Color(246, 248, 139));
                boolean isEven = false;
                Style even = doc.addStyle(null, null);
                even.addAttribute(StyleConstants.Background, UIManager.get("Panel.background"));
                if (filterer == null) {
                    return; // #101776
                }
                for (String hit : filterer.getMatchesFor(filterText, deps[0])) {
                    int loc = doc.getLength();
                    doc.insertString(loc, hit, (isEven ? even : null));
                    int start = (matchCase?hit:hit.toLowerCase(Locale.US)).indexOf(filterTextLC);
                    while (start != -1) {
                        doc.setCharacterAttributes(loc + start, filterTextLC.length(), match, true);
                        start = hit.toLowerCase(Locale.US).indexOf(filterTextLC, start + 1);
                    }
                    doc.insertString(doc.getLength(), "\n", (isEven ? even : null)); // NOI18N
                    isEven ^= true;
                }
            } else {
                Style italics = doc.addStyle(null, null);
                italics.addAttribute(StyleConstants.Italic, Boolean.TRUE);
                doc.insertString(doc.getLength(), getMessage("TEXT_no_filter_specified"), italics);
            }
        }
        descValue.setCaretPosition(0);
    } catch (BadLocationException e) {
        Util.err.notify(ErrorManager.INFORMATIONAL, e);
    }
}
 
Example 18
Source File: MiscEditorUtil.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Test whether the line is in JavaScript source.
 * @param line The line to test
 * @return <code>true</code> when the line is in JavaScript source, <code>false</code> otherwise.
 */
public static boolean isInJavaScript(Line line) {
    LOG.log(Level.FINER, "\nisInJavaScript({0}):", line);
    FileObject fo = line.getLookup().lookup(FileObject.class);
    if (isJavascriptSource(fo)) {
        LOG.fine("is JavaScript source file => true");
        return true;
    }
    EditorCookie editorCookie = line.getLookup().lookup(EditorCookie.class);
    StyledDocument document = editorCookie.getDocument();
    Boolean isJS = null;
    ((AbstractDocument) document).readLock();
    try {
        TokenHierarchy<Document> th = TokenHierarchy.get((Document) document);
        int ln = line.getLineNumber();
        int offset = NbDocument.findLineOffset(document, ln);
        int maxOffset = document.getLength() - 1;
        int maxLine = NbDocument.findLineNumber(document, maxOffset);
        int offset2;
        if (ln + 1 > maxLine) {
            offset2 = maxOffset;
        } else {
            offset2 = NbDocument.findLineOffset(document, ln+1) - 1;
        }
        // The line has offsets <offset, offset2>
        Set<LanguagePath> languagePaths = th.languagePaths();
        for (LanguagePath lp : languagePaths) {
            List<TokenSequence<?>> tsl = th.tokenSequenceList(lp, offset, offset2);
            for (TokenSequence ts : tsl) {
                if (ts.moveNext()) {
                    /*int to = ts.offset();
                    if (LOG.isLoggable(Level.FINER)) {
                        LOG.finer("Token offset = "+to+", offsets = <"+offset+", "+offset2+">, mimeType = "+ts.language().mimeType());
                    }
                    if (!(offset <= to && to < offset2)) {
                        continue;
                    }*/
                    TokenSequence ets;
                    ets = ts.embedded();
                    if (ets != null) {
                        ts = ets;
                    }
                    String mimeType = ts.language().mimeType();
                    LOG.log(Level.FINER, "Have language {0}", mimeType);
                    if (isJS == null && JAVASCRIPT_MIME_TYPE.equals(mimeType)) {
                        isJS = true;
                        if (!LOG.isLoggable(Level.FINER)) {
                            break;
                        }
                    }
                }
            }
        }
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    LOG.log(Level.FINER, "isJS = {0}", isJS);
    return isJS != null && isJS;
}
 
Example 19
Source File: PositionBounds.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Inserts the text after this PositionBounds.
* @param text The text to insert. The text must not be empty.
* @return the range of inserted text.
* @exception IOException if any problem occurred during document loading (if that was necessary)
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public PositionBounds insertAfter(final String text)
throws IOException, BadLocationException {
    if (text.length() == 0) {
        throw new BadLocationException(
            NbBundle.getBundle(PositionBounds.class).getString("MSG_Empty_string"), begin.getOffset()
        );
    }

    final CloneableEditorSupport editor = begin.getCloneableEditorSupport();
    final StyledDocument doc = editor.openDocument();
    final Object[] hold = new Object[] { null, null };

    Runnable run = new Runnable() {
            public void run() {
                synchronized (editor.getLock()) {
                    /* editor.getLock(): fixes deadlock - this lock is acquired later anyhow,
                    so we are changing the order in which the locks are acquired */
                    try {
                        // [MaM] remember doclen to compute new length
                        // of the inserted string (the length changes
                        // because insertString removes \r characters
                        // from it)
                        int docLen = doc.getLength();

                        int p1 = end.getOffset();
                        doc.insertString(p1, text, null);

                        int p2 = (p1 + doc.getLength()) - docLen;

                        end = editor.createPositionRef(p1, end.getPositionBias());

                        PositionRef posBegin = editor.createPositionRef(p1, Position.Bias.Forward);
                        PositionRef posEnd = editor.createPositionRef(p2, Position.Bias.Backward);
                        hold[1] = new PositionBounds(posBegin, posEnd);
                    } catch (BadLocationException e) {
                        hold[0] = e;
                    }
                }
            }
        };

    NbDocument.runAtomic(doc, run);

    if (hold[0] != null) {
        throw (BadLocationException) hold[0];
    } else {
        return (PositionBounds) hold[1];
    }
}
 
Example 20
Source File: PositionBounds.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Replaces the text contained in this range.
* This replacement is done atomically, and so is preferable to manual inserts & removes.
* <p>If you are running this from user-oriented code, you may want to wrap it in {@link NbDocument#runAtomicAsUser}.
* @param text new text to insert over existing text
* @exception IOException if any problem occurred during document loading (if that was necessary)
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public void setText(final String text) throws IOException, BadLocationException {
    final CloneableEditorSupport editor = begin.getCloneableEditorSupport();
    final StyledDocument doc = editor.openDocument();
    final BadLocationException[] hold = new BadLocationException[] { null };
    Runnable run = new Runnable() {
            public void run() {
                try {
                    int p1 = begin.getOffset();
                    int p2 = end.getOffset();
                    int len = text.length();

                    if (len == 0) { // 1) set empty string

                        if (p2 > p1) {
                            doc.remove(p1, p2 - p1);
                        }
                    } else { // 2) set non empty string

                        int docLen = doc.getLength();

                        if ((p2 - p1) >= 2) {
                            doc.insertString(p1 + 1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;
                            doc.remove(p1 + 1 + len, p2 - p1 - 1);
                            doc.remove(p1, 1);
                        } else {
                            // zero or exactly one character:
                            // adjust the positions if they are
                            // biased to not absorb the text inserted at the start/end
                            // it would be ridiculous not to have text set by setText
                            // be part of the bounds.
                            doc.insertString(p1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;

                            if (p2 > p1) {
                                doc.remove(p1 + len, p2 - p1);
                            }

                            if (begin.getOffset() != p1) {
                                begin = editor.createPositionRef(p1, begin.getPositionBias());
                            }

                            if ((end.getOffset() - p1) != len) {
                                end = editor.createPositionRef(p1 + len, end.getPositionBias());
                            }
                        }
                    }
                } catch (BadLocationException e) {
                    hold[0] = e;
                }
            }
        };

    NbDocument.runAtomic(doc, run);

    if (hold[0] != null) {
        throw hold[0];
    }
}