delete(false);
}
if (document.getCharacterCount() == 0) {
// the document is currently empty
Paragraph paragraph = new Paragraph();
paragraph.add(text);
document.insert(paragraph, 0);
} else {
Node descendant = document.getDescendantAt(selectionStart);
int offset = selectionStart - descendant.getDocumentOffset();
if (descendant instanceof TextNode) {
// The caret is positioned within an existing text node
TextNode textNode = (TextNode)descendant;
textNode.insertText(text, offset);
} else if (descendant instanceof Paragraph) {
// The caret is positioned on the paragraph terminator
// so get to the bottom rightmost descendant and add there
Paragraph paragraph = (Paragraph)descendant;
Node node = getRightmostDescendant(paragraph);
if (node instanceof TextNode) {
// Insert the text into the existing node
TextNode textNode = (TextNode)node;
textNode.insertText(text, selectionStart - textNode.getDocumentOffset());
} else if (node instanceof Element) {
// Append a new text node
Element element = (Element)node;
element.add(new TextNode(text));
} else {
// The paragraph is currently empty
paragraph.add(new TextNode(text));
}
} else {
// The caret is positioned on a non-text character node; insert
// the text into the descendant's parent
Element parent = descendant.getParent();