try {
DocumentContext<ContentNode, ContentElement, ContentTextNode> cxt =
container.getContext();
ContentElement element = child.asElement();
if (element != null && isLineElement(element)) {
Line line = new Line(cxt, element);
ContentNode previousDirectSibling = child.getPreviousSibling();
ContentNode previousPersistentSibling = container.getMutableDoc().getPreviousSibling(child);
if (previousPersistentSibling == null) {
insertAsFirstLine(container, line);
} else {
Line previousLine;
if (element.getParentElement() == container) {
// TODO(danilatos): Handle the case where this assertion fails.
assert previousDirectSibling != null &&
LineRendering.isLocalParagraph(previousDirectSibling);
previousLine = Line.fromParagraph(previousDirectSibling.asElement());
} else {
previousLine = Line.fromParagraph(element.getParentElement());
}
// TODO(danilatos): Handle the case where this assertion fails too.
assert previousLine != null;
insertAfterLine(previousLine, line);
}
Line nextLine = line.next();
ContentElement paragraph = line.getParagraph();
if (element.getParentElement() != container) {
cxt.annotatableContent().transparentMove(paragraph, paragraph.getNextSibling(),
null, null);
cxt.annotatableContent().transparentMove(container, paragraph, null,
element.getParentElement().getNextSibling());
cxt.annotatableContent().transparentMove(container, element, null,
paragraph);
}
} else {
ContentNode before = child.getPreviousSibling();
ContentElement paragraph = before == null ? null : asParagraph(before);
if (paragraph != null) {
cxt.annotatableContent().transparentMove(paragraph, child, child.getNextSibling(), null);
}
}