Node descendant = document.getDescendantAt(offset);
if (selectionLength == 0
&& descendant instanceof Paragraph) {
// We are deleting a paragraph terminator
Paragraph paragraph = (Paragraph)descendant;
Element parent = paragraph.getParent();
int index = parent.indexOf(paragraph);
// Attempt to merge any successive content into the paragraph
if (index < parent.getLength() - 1) {
// TODO This won't always be a paragraph - we'll need to
// find the next paragraph by walking the tree, then
// remove any empty nodes
Sequence<Node> removed = parent.remove(index + 1, 1);
Paragraph nextParagraph = (Paragraph)removed.get(0);
paragraph.insertRange(nextParagraph, paragraph.getCharacterCount() - 1);
}
} else {
document.removeRange(offset, characterCount);
}
}
// Ensure that the document remains editable
if (document.getCharacterCount() == 0) {
document.add(new Paragraph(""));
}
// Move the caret to the merge point
if (offset >= 0) {
setSelection(offset, 0);