}
private void prepareParagraphContainer(int leftLength, int index) throws Exception {
OdfElement rightparentElement = textSelection.getContainerElement();
int nodeLength = TextExtractor.getText(rightparentElement).length();
Paragraph orgparagraph = Paragraph.getInstanceof((TextParagraphElementBase) rightparentElement);
TextDocument document = (TextDocument) orgparagraph.getOwnerDocument();
OfficeTextElement sroot = sourceDocument.getContentRoot();
NodeList clist = sroot.getChildNodes();
try {
OfficeTextElement documentRoot = document.getContentRoot();
Node rootNode = rightparentElement.getParentNode();
if (!rootNode.equals(documentRoot)) {
throw new RuntimeException(
"The ParentNode of text content's ContainerElement which will be replaced is not Document ContentRoot, TextDocument only can be insert to the Docuemnt ContentRoot");
}
} catch (Exception e) {
Logger.getLogger(TextDocumentSelection.class.getName()).log(Level.SEVERE, e.getMessage(), e);
}
if (index == 0) {
if (leftLength == nodeLength) {
// Replace whole Paragraph
OdfElement refElement = orgparagraph.getOdfElement();
for (int i = 0; i < clist.getLength(); i++) {
OdfElement node = (OdfElement) clist.item(i);
refElement = document.insertOdfElement(refElement,
sourceDocument, node, false);
}
rightparentElement.getParentNode().removeChild(
rightparentElement);
} else {
// at the start of original Paragraph, insert before original
// Paragraph
delete(index, leftLength, rightparentElement);
for (int i = 0; i < clist.getLength(); i++) {
OdfElement node = (OdfElement) clist.item(i);
document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, true);
}
}
} else if (nodeLength == (index + leftLength)) {
// at the end of original Paragraph, insert after original Paragraph
delete(index, leftLength, rightparentElement);
for (int i = 0; i < clist.getLength(); i++) {
OdfElement node = (OdfElement) clist.item(i);
document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, false);
}
} else {
// at the middle of original Paragraph, split original Paragraph,
// insert before the second Paragraph.
delete(index, leftLength, rightparentElement);
Node leftparentElement = rightparentElement.cloneNode(true);
rightparentElement.getParentNode().insertBefore(leftparentElement, rightparentElement);
nodeLength = TextExtractor.getText((OdfElement) leftparentElement).length();
delete(index, nodeLength - index, leftparentElement);
delete(0, index, rightparentElement);
for (int i = 0; i < clist.getLength(); i++) {
OdfElement node = (OdfElement) clist.item(i);
document.insertOdfElement(orgparagraph.getOdfElement(), sourceDocument, node, true);
}
int offset = 0 - leftLength - index;
SelectionManager.refresh(rightparentElement, offset, offset);
}
}