// TODO Make this part of the undoable action (for all such
// actions)
document.removeRange(selectionStart, selectionLength);
}
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
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 {