// 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
Paragraph paragraph = (Paragraph)descendant;
int n = paragraph.getLength();
if (n > 0) {
Node node = paragraph.get(n - 1);
if (node instanceof TextNode) {
// Insert the text into the existing node
TextNode textNode = (TextNode)node;
textNode.insertText(text, offset);
} else {
// Append a new text node
paragraph.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();