This source file includes following definitions.
- hasInterchangeNewlineAtStart
- hasInterchangeNewlineAtEnd
- isInterchangeNewlineNode
- isInterchangeConvertedSpaceSpan
- positionAvoidingPrecedingNodes
- m_hasInterchangeNewlineAtEnd
- isEmpty
- firstChild
- lastChild
- removeNodePreservingChildren
- removeNode
- insertNodeBefore
- insertFragmentForTestRendering
- restoreAndRemoveTestRenderingNodesToFragment
- removeUnrenderedNodes
- removeInterchangeNodes
- respondToNodeInsertion
- willRemoveNodePreservingChildren
- willRemoveNode
- didReplaceNode
- m_shouldMergeEnd
- hasMatchingQuoteLevel
- shouldMergeStart
- shouldMergeEnd
- isMailPasteAsQuotationNode
- isHeaderElement
- haveSameTagName
- shouldMerge
- removeRedundantStylesAndKeepStyleSpanInline
- isProhibitedParagraphChild
- makeInsertedContentRoundTrippableWithHTMLTreeBuilder
- moveNodeOutOfAncestor
- nodeHasVisibleRenderText
- removeUnrenderedTextNodesAtEnds
- positionAtEndOfInsertedContent
- positionAtStartOfInsertedContent
- removeHeadContents
- handleStyleSpansBeforeInsertion
- handleStyleSpans
- mergeEndIfNeeded
- enclosingInline
- isInlineNodeWithStyle
- nodeToSplitToAvoidPastingIntoInlineNodesWithStyle
- doApply
- shouldRemoveEndBR
- shouldPerformSmartReplace
- isCharacterSmartReplaceExemptConsideringNonBreakingSpace
- addSpacesForSmartReplace
- completeHTMLReplacement
- mergeTextNodesAroundPosition
- editingAction
- insertAsListItems
- updateNodesInserted
- performTrivialReplace
#include "config.h"
#include "core/editing/ReplaceSelectionCommand.h"
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentFragment.h"
#include "core/dom/Element.h"
#include "core/dom/Text.h"
#include "core/editing/ApplyStyleCommand.h"
#include "core/editing/BreakBlockquoteCommand.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/HTMLInterchange.h"
#include "core/editing/SimplifyMarkupCommand.h"
#include "core/editing/SmartReplace.h"
#include "core/editing/TextIterator.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
#include "core/events/BeforeTextInsertedEvent.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderText.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
namespace WebCore {
using namespace HTMLNames;
enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
class ReplacementFragment {
WTF_MAKE_NONCOPYABLE(ReplacementFragment);
public:
ReplacementFragment(Document*, DocumentFragment*, const VisibleSelection&);
Node* firstChild() const;
Node* lastChild() const;
bool isEmpty() const;
bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
void removeNode(PassRefPtr<Node>);
void removeNodePreservingChildren(PassRefPtr<Node>);
private:
PassRefPtr<Element> insertFragmentForTestRendering(Node* rootEditableNode);
void removeUnrenderedNodes(Node*);
void restoreAndRemoveTestRenderingNodesToFragment(Element*);
void removeInterchangeNodes(Node*);
void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
RefPtr<Document> m_document;
RefPtr<DocumentFragment> m_fragment;
bool m_hasInterchangeNewlineAtStart;
bool m_hasInterchangeNewlineAtEnd;
};
static bool isInterchangeNewlineNode(const Node *node)
{
DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
return isHTMLBRElement(node) && toElement(node)->getAttribute(classAttr) == interchangeNewlineClassString;
}
static bool isInterchangeConvertedSpaceSpan(const Node *node)
{
DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
return node->isHTMLElement() && toHTMLElement(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
}
static Position positionAvoidingPrecedingNodes(Position pos)
{
if (editingIgnoresContent(pos.deprecatedNode()))
return pos;
Node* enclosingBlockNode = enclosingBlock(pos.containerNode());
for (Position nextPosition = pos; nextPosition.containerNode() != enclosingBlockNode; pos = nextPosition) {
if (lineBreakExistsAtPosition(pos))
break;
if (pos.containerNode()->nonShadowBoundaryParentNode())
nextPosition = positionInParentAfterNode(*pos.containerNode());
if (nextPosition == pos
|| enclosingBlock(nextPosition.containerNode()) != enclosingBlockNode
|| VisiblePosition(pos) != VisiblePosition(nextPosition))
break;
}
return pos;
}
ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, const VisibleSelection& selection)
: m_document(document),
m_fragment(fragment),
m_hasInterchangeNewlineAtStart(false),
m_hasInterchangeNewlineAtEnd(false)
{
if (!m_document)
return;
if (!m_fragment)
return;
if (!m_fragment->firstChild())
return;
RefPtr<Element> editableRoot = selection.rootEditableElement();
ASSERT(editableRoot);
if (!editableRoot)
return;
Node* shadowAncestorNode = editableRoot->deprecatedShadowAncestorNode();
if (!editableRoot->getAttributeEventListener(EventTypeNames::webkitBeforeTextInserted) &&
!(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
editableRoot->rendererIsRichlyEditable()) {
removeInterchangeNodes(m_fragment.get());
return;
}
RefPtr<Element> holder = insertFragmentForTestRendering(editableRoot.get());
if (!holder) {
removeInterchangeNodes(m_fragment.get());
return;
}
RefPtrWillBeRawPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
String text = plainText(range.get(), static_cast<TextIteratorBehavior>(TextIteratorEmitsOriginalText | TextIteratorIgnoresStyleVisibility));
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
RefPtrWillBeRawPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
editableRoot->dispatchEvent(evt, ASSERT_NO_EXCEPTION);
if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
if (!m_fragment->firstChild())
return;
holder = insertFragmentForTestRendering(editableRoot.get());
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
}
}
bool ReplacementFragment::isEmpty() const
{
return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
}
Node *ReplacementFragment::firstChild() const
{
return m_fragment ? m_fragment->firstChild() : 0;
}
Node *ReplacementFragment::lastChild() const
{
return m_fragment ? m_fragment->lastChild() : 0;
}
void ReplacementFragment::removeNodePreservingChildren(PassRefPtr<Node> node)
{
if (!node)
return;
while (RefPtr<Node> n = node->firstChild()) {
removeNode(n);
insertNodeBefore(n.release(), node.get());
}
removeNode(node);
}
void ReplacementFragment::removeNode(PassRefPtr<Node> node)
{
if (!node)
return;
ContainerNode* parent = node->nonShadowBoundaryParentNode();
if (!parent)
return;
parent->removeChild(node.get());
}
void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
{
if (!node || !refNode)
return;
ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
if (!parent)
return;
parent->insertBefore(node, refNode);
}
PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
{
ASSERT(m_document);
RefPtr<Element> holder = createDefaultParagraphElement(*m_document.get());
holder->appendChild(m_fragment);
rootEditableElement->appendChild(holder.get());
m_document->updateLayoutIgnorePendingStylesheets();
return holder.release();
}
void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(Element* holder)
{
if (!holder)
return;
while (RefPtr<Node> node = holder->firstChild()) {
holder->removeChild(node.get());
m_fragment->appendChild(node.get());
}
removeNode(holder);
}
void ReplacementFragment::removeUnrenderedNodes(Node* holder)
{
Vector<RefPtr<Node> > unrendered;
for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder))
if (!isNodeRendered(node) && !isTableStructureNode(node))
unrendered.append(node);
size_t n = unrendered.size();
for (size_t i = 0; i < n; ++i)
removeNode(unrendered[i]);
}
void ReplacementFragment::removeInterchangeNodes(Node* container)
{
m_hasInterchangeNewlineAtStart = false;
m_hasInterchangeNewlineAtEnd = false;
Node* node = container->firstChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtStart = true;
removeNode(node);
break;
}
node = node->firstChild();
}
if (!container->hasChildren())
return;
node = container->lastChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtEnd = true;
removeNode(node);
break;
}
node = node->lastChild();
}
node = container->firstChild();
while (node) {
RefPtr<Node> next = NodeTraversal::next(*node);
if (isInterchangeConvertedSpaceSpan(node)) {
next = NodeTraversal::nextSkippingChildren(*node);
removeNodePreservingChildren(node);
}
node = next.get();
}
}
inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node& node)
{
if (!m_firstNodeInserted)
m_firstNodeInserted = &node;
m_lastNodeInserted = &node;
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node& node)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::next(node);
if (m_lastNodeInserted == node)
m_lastNodeInserted = node.lastChild() ? node.lastChild() : NodeTraversal::nextSkippingChildren(node);
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node& node)
{
if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
m_firstNodeInserted = nullptr;
m_lastNodeInserted = nullptr;
} else if (m_firstNodeInserted == node) {
m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
} else if (m_lastNodeInserted == node) {
m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
}
}
inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node& node, Node& newNode)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = &newNode;
if (m_lastNodeInserted == node)
m_lastNodeInserted = &newNode;
}
ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
: CompositeEditCommand(document)
, m_selectReplacement(options & SelectReplacement)
, m_smartReplace(options & SmartReplace)
, m_matchStyle(options & MatchStyle)
, m_documentFragment(fragment)
, m_preventNesting(options & PreventNesting)
, m_movingParagraph(options & MovingParagraph)
, m_editAction(editAction)
, m_sanitizeFragment(options & SanitizeFragment)
, m_shouldMergeEnd(false)
{
}
static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
{
Position existing = endOfExistingContent.deepEquivalent();
Position inserted = endOfInsertedContent.deepEquivalent();
bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
}
bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
{
if (m_movingParagraph)
return false;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
if (prev.isNull())
return false;
if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
return true;
return !selectionStartWasStartOfParagraph
&& !fragmentHasInterchangeNewlineAtStart
&& isStartOfParagraph(startOfInsertedContent)
&& !isHTMLBRElement(*startOfInsertedContent.deepEquivalent().deprecatedNode())
&& shouldMerge(startOfInsertedContent, prev);
}
bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
{
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
if (next.isNull())
return false;
return !selectionEndWasEndOfParagraph
&& isEndOfParagraph(endOfInsertedContent)
&& !isHTMLBRElement(*endOfInsertedContent.deepEquivalent().deprecatedNode())
&& shouldMerge(endOfInsertedContent, next);
}
static bool isMailPasteAsQuotationNode(const Node* node)
{
return node && node->hasTagName(blockquoteTag) && toElement(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
}
static bool isHeaderElement(const Node* a)
{
if (!a)
return false;
return a->hasTagName(h1Tag)
|| a->hasTagName(h2Tag)
|| a->hasTagName(h3Tag)
|| a->hasTagName(h4Tag)
|| a->hasTagName(h5Tag)
|| a->hasTagName(h6Tag);
}
static bool haveSameTagName(Node* a, Node* b)
{
return a && b && a->isElementNode() && b->isElementNode() && toElement(a)->tagName() == toElement(b)->tagName();
}
bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
{
if (source.isNull() || destination.isNull())
return false;
Node* sourceNode = source.deepEquivalent().deprecatedNode();
Node* destinationNode = destination.deepEquivalent().deprecatedNode();
Node* sourceBlock = enclosingBlock(sourceNode);
Node* destinationBlock = enclosingBlock(destinationNode);
return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) &&
enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
(!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
!isBlock(sourceNode) && !isBlock(destinationNode);
}
void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
next = NodeTraversal::next(*node);
if (!node->isStyledElement())
continue;
Element* element = toElement(node);
const StylePropertySet* inlineStyle = element->inlineStyle();
RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
if (inlineStyle) {
if (element->isHTMLElement()) {
Vector<QualifiedName> attributes;
HTMLElement* htmlElement = toHTMLElement(element);
ASSERT(htmlElement);
if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
element = toElement(node);
inlineStyle = element->inlineStyle();
insertedNodes.didReplaceNode(*htmlElement, *node);
} else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
EditingStyle::DoNotExtractMatchingStyle)) {
for (size_t i = 0; i < attributes.size(); i++)
removeNodeAttribute(element, attributes[i]);
}
}
ContainerNode* context = element->parentNode();
Node* blockquoteNode = !context || isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
newInlineStyle->removeStyleFromRulesAndContext(element, document().documentElement());
newInlineStyle->removeStyleFromRulesAndContext(element, context);
}
if (!inlineStyle || newInlineStyle->isEmpty()) {
if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
removeNodeAttribute(element, styleAttr);
} else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount()) {
setNodeAttribute(element, styleAttr, AtomicString(newInlineStyle->style()->asText()));
}
if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
&& VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
&& VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
if (element->parentNode() && element->parentNode()->rendererIsRichlyEditable())
removeNodeAttribute(element, contenteditableAttr);
if (isLegacyAppleStyleSpan(element)) {
if (!element->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
if (isBlock(element))
element->style()->setPropertyInternal(CSSPropertyDisplay, "inline", false, IGNORE_EXCEPTION);
if (element->renderer() && element->renderer()->style()->isFloating())
element->style()->setPropertyInternal(CSSPropertyFloat, "none", false, IGNORE_EXCEPTION);
}
}
}
static bool isProhibitedParagraphChild(const AtomicString& name)
{
DEFINE_STATIC_LOCAL(HashSet<AtomicString>, elements, ());
if (elements.isEmpty()) {
elements.add(addressTag.localName());
elements.add(articleTag.localName());
elements.add(asideTag.localName());
elements.add(blockquoteTag.localName());
elements.add(captionTag.localName());
elements.add(centerTag.localName());
elements.add(colTag.localName());
elements.add(colgroupTag.localName());
elements.add(ddTag.localName());
elements.add(detailsTag.localName());
elements.add(dirTag.localName());
elements.add(divTag.localName());
elements.add(dlTag.localName());
elements.add(dtTag.localName());
elements.add(fieldsetTag.localName());
elements.add(figcaptionTag.localName());
elements.add(figureTag.localName());
elements.add(footerTag.localName());
elements.add(formTag.localName());
elements.add(h1Tag.localName());
elements.add(h2Tag.localName());
elements.add(h3Tag.localName());
elements.add(h4Tag.localName());
elements.add(h5Tag.localName());
elements.add(h6Tag.localName());
elements.add(headerTag.localName());
elements.add(hgroupTag.localName());
elements.add(hrTag.localName());
elements.add(liTag.localName());
elements.add(listingTag.localName());
elements.add(mainTag.localName());
elements.add(menuTag.localName());
elements.add(navTag.localName());
elements.add(olTag.localName());
elements.add(pTag.localName());
elements.add(plaintextTag.localName());
elements.add(preTag.localName());
elements.add(sectionTag.localName());
elements.add(summaryTag.localName());
elements.add(tableTag.localName());
elements.add(tbodyTag.localName());
elements.add(tdTag.localName());
elements.add(tfootTag.localName());
elements.add(thTag.localName());
elements.add(theadTag.localName());
elements.add(trTag.localName());
elements.add(ulTag.localName());
elements.add(xmpTag.localName());
}
return elements.contains(name);
}
void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(const InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
next = NodeTraversal::next(*node);
if (!node->isHTMLElement())
continue;
if (isProhibitedParagraphChild(toHTMLElement(node)->localName())) {
if (HTMLElement* paragraphElement = toHTMLElement(enclosingNodeWithTag(positionInParentBeforeNode(*node), pTag)))
moveNodeOutOfAncestor(node, paragraphElement);
}
if (isHeaderElement(node.get())) {
if (HTMLElement* headerElement = toHTMLElement(highestEnclosingNodeOfType(positionInParentBeforeNode(*node), isHeaderElement)))
moveNodeOutOfAncestor(node, headerElement);
}
}
}
void ReplaceSelectionCommand::moveNodeOutOfAncestor(PassRefPtr<Node> prpNode, PassRefPtr<Node> prpAncestor)
{
RefPtr<Node> node = prpNode;
RefPtr<Node> ancestor = prpAncestor;
if (!ancestor->parentNode()->rendererIsEditable())
return;
VisiblePosition positionAtEndOfNode(lastPositionInOrAfterNode(node.get()));
VisiblePosition lastPositionInParagraph(lastPositionInNode(ancestor.get()));
if (positionAtEndOfNode == lastPositionInParagraph) {
removeNode(node);
if (ancestor->nextSibling())
insertNodeBefore(node, ancestor->nextSibling());
else
appendNode(node, ancestor->parentNode());
} else {
RefPtr<Node> nodeToSplitTo = splitTreeToNode(node.get(), ancestor.get(), true);
removeNode(node);
insertNodeBefore(node, nodeToSplitTo);
}
if (!ancestor->firstChild())
removeNode(ancestor.release());
}
static inline bool nodeHasVisibleRenderText(Text& text)
{
return text.renderer() && toRenderText(text.renderer())->renderedTextLength() > 0;
}
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
{
document().updateLayoutIgnorePendingStylesheets();
Node* lastLeafInserted = insertedNodes.lastLeafInserted();
if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*lastLeafInserted))
&& !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
&& !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
insertedNodes.willRemoveNode(*lastLeafInserted);
removeNode(lastLeafInserted);
}
Node* firstNodeInserted = insertedNodes.firstNodeInserted();
if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*firstNodeInserted))) {
insertedNodes.willRemoveNode(*firstNodeInserted);
removeNode(firstNodeInserted);
}
}
VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
{
Node* enclosingSelect = enclosingNodeWithTag(m_endOfInsertedContent, selectTag);
return VisiblePosition(enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent);
}
VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
{
return VisiblePosition(m_startOfInsertedContent);
}
static void removeHeadContents(ReplacementFragment& fragment)
{
Node* next = 0;
for (Node* node = fragment.firstChild(); node; node = next) {
if (isHTMLBaseElement(*node)
|| isHTMLLinkElement(*node)
|| isHTMLMetaElement(*node)
|| isHTMLStyleElement(*node)
|| isHTMLTitleElement(*node)) {
next = NodeTraversal::nextSkippingChildren(*node);
fragment.removeNode(node);
} else {
next = NodeTraversal::next(*node);
}
}
}
static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
{
Node* topNode = fragment.firstChild();
if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
return false;
if (!isLegacyAppleStyleSpan(topNode))
return false;
Node* wrappingStyleSpan = topNode;
RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
String styleText = styleAtInsertionPos->style()->asText();
if (styleText != toElement(wrappingStyleSpan)->getAttribute(styleAttr))
return false;
fragment.removeNodePreservingChildren(wrappingStyleSpan);
return true;
}
void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
{
HTMLElement* wrappingStyleSpan = 0;
for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
if (isLegacyAppleStyleSpan(node)) {
wrappingStyleSpan = toHTMLElement(node);
break;
}
}
if (!wrappingStyleSpan)
return;
RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->inlineStyle());
ContainerNode* context = wrappingStyleSpan->parentNode();
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
context = document().documentElement();
style->prepareToApplyAt(firstPositionInNode(context));
style->removeBlockProperties();
if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
removeNodePreservingChildren(wrappingStyleSpan);
} else {
setNodeAttribute(wrappingStyleSpan, styleAttr, AtomicString(style->style()->asText()));
}
}
void ReplaceSelectionCommand::mergeEndIfNeeded()
{
if (!m_shouldMergeEnd)
return;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
if (m_movingParagraph) {
ASSERT_NOT_REACHED();
return;
}
bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
if (endOfParagraph(startOfParagraphToMove) == destination) {
RefPtr<Node> placeholder = createBreakElement(document());
insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
destination = VisiblePosition(positionBeforeNode(placeholder.get()));
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
if (mergeForward) {
if (m_startOfInsertedContent.isOrphan())
m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
if (m_endOfInsertedContent.isNull())
m_endOfInsertedContent = m_startOfInsertedContent;
}
}
static Node* enclosingInline(Node* node)
{
while (ContainerNode* parent = node->parentNode()) {
if (parent->isBlockFlowElement() || isHTMLBodyElement(*parent))
return node;
for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
if (sibling->isBlockFlowElement())
return node;
}
node = parent;
}
return node;
}
static bool isInlineNodeWithStyle(const Node* node)
{
if (isBlock(node))
return false;
if (!node->isHTMLElement())
return false;
const HTMLElement* element = toHTMLElement(node);
const AtomicString& classAttributeValue = element->getAttribute(classAttr);
if (classAttributeValue == AppleTabSpanClass
|| classAttributeValue == AppleConvertedSpace
|| classAttributeValue == ApplePasteAsQuotation)
return true;
return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
}
inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
{
Node* containgBlock = enclosingBlock(insertionPos.containerNode());
return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
}
void ReplaceSelectionCommand::doApply()
{
VisibleSelection selection = endingSelection();
ASSERT(selection.isCaretOrRange());
ASSERT(selection.start().deprecatedNode());
if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
return;
if (!selection.rootEditableElement())
return;
ReplacementFragment fragment(&document(), m_documentFragment.get(), selection);
if (performTrivialReplace(fragment))
return;
if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
&& (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
m_matchStyle = false;
if (m_matchStyle) {
m_insertionStyle = EditingStyle::create(selection.start());
m_insertionStyle->mergeTypingStyle(&document());
}
VisiblePosition visibleStart = selection.visibleStart();
VisiblePosition visibleEnd = selection.visibleEnd();
bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
Position insertionPos = selection.start();
bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
bool selectionIsPlainText = !selection.isContentRichlyEditable();
Element* currentRoot = selection.rootEditableElement();
if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
m_preventNesting = false;
if (selection.isRange()) {
bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
deleteSelection(false, mergeBlocksAfterDelete, false);
visibleStart = endingSelection().visibleStart();
if (fragment.hasInterchangeNewlineAtStart()) {
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
if (!isEndOfEditableOrNonEditableContent(visibleStart))
setEndingSelection(visibleStart.next());
} else
insertParagraphSeparator();
}
insertionPos = endingSelection().start();
} else {
ASSERT(selection.isCaret());
if (fragment.hasInterchangeNewlineAtStart()) {
VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
setEndingSelection(next);
else {
insertParagraphSeparator();
visibleStart = endingSelection().visibleStart();
}
}
if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
insertParagraphSeparator();
setEndingSelection(endingSelection().visibleStart().previous());
}
insertionPos = endingSelection().start();
}
if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
applyCommandToComposite(BreakBlockquoteCommand::create(document()));
Node* br = endingSelection().start().deprecatedNode();
ASSERT(isHTMLBRElement(br));
insertionPos = positionInParentBeforeNode(*br);
removeNode(br);
}
prepareWhitespaceAtPositionForSplit(insertionPos);
if (!insertionPos.downstream().deprecatedNode())
return;
Node* endBR = isHTMLBRElement(*insertionPos.downstream().deprecatedNode()) ? insertionPos.downstream().deprecatedNode() : 0;
VisiblePosition originalVisPosBeforeEndBR;
if (endBR)
originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
RefPtr<Node> insertionBlock = enclosingBlock(insertionPos.deprecatedNode());
if (m_preventNesting && insertionBlock && !isTableCell(insertionBlock.get()) && !startIsInsideMailBlockquote) {
ASSERT(insertionBlock != currentRoot);
VisiblePosition visibleInsertionPos(insertionPos);
if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
insertionPos = positionInParentAfterNode(*insertionBlock);
else if (isStartOfBlock(visibleInsertionPos))
insertionPos = positionInParentBeforeNode(*insertionBlock);
}
insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
if (LocalFrame* frame = document().frame())
frame->selection().clearTypingStyle();
removeHeadContents(fragment);
insertionPos = positionAvoidingPrecedingNodes(insertionPos);
insertionPos = positionOutsideTabSpan(insertionPos);
bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
if (fragment.isEmpty() || !fragment.firstChild())
return;
if (!m_matchStyle && !enclosingList(insertionPos.containerNode())) {
if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
splitTextNode(insertionPos.containerText(), insertionPos.offsetInContainerNode());
insertionPos = firstPositionInNode(insertionPos.containerNode());
}
if (RefPtr<Node> nodeToSplitTo = nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(insertionPos)) {
if (insertionPos.containerNode() != nodeToSplitTo->parentNode()) {
Node* splitStart = insertionPos.computeNodeAfterPosition();
if (!splitStart)
splitStart = insertionPos.containerNode();
nodeToSplitTo = splitTreeToNode(splitStart, nodeToSplitTo->parentNode()).get();
insertionPos = positionInParentBeforeNode(*nodeToSplitTo);
}
}
}
InsertedNodes insertedNodes;
RefPtr<Node> refNode = fragment.firstChild();
ASSERT(refNode);
RefPtr<Node> node = refNode->nextSibling();
fragment.removeNode(refNode);
Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
&& blockStart && blockStart->renderer()->isListItem())
refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
else {
insertNodeAt(refNode, insertionPos);
insertedNodes.respondToNodeInsertion(*refNode);
}
if (!refNode->inDocument())
return;
bool plainTextFragment = isPlainTextMarkup(refNode.get());
while (node) {
RefPtr<Node> next = node->nextSibling();
fragment.removeNode(node.get());
insertNodeAfter(node, refNode);
insertedNodes.respondToNodeInsertion(*node);
if (!node->inDocument())
return;
refNode = node;
if (node && plainTextFragment)
plainTextFragment = isPlainTextMarkup(node.get());
node = next;
}
removeUnrenderedTextNodesAtEnds(insertedNodes);
if (!handledStyleSpans)
handleStyleSpans(insertedNodes);
if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
return;
if (insertionBlock && !insertionBlock->inDocument())
insertionBlock = nullptr;
VisiblePosition startOfInsertedContent(firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted()));
if (!startOfInsertedContent.isNull() && insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
if (endBR && (plainTextFragment || (shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR) && !(fragment.hasInterchangeNewlineAtEnd() && selectionIsPlainText)))) {
RefPtr<Node> parent = endBR->parentNode();
insertedNodes.willRemoveNode(*endBR);
removeNode(endBR);
if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
insertedNodes.willRemoveNode(*nodeToRemove);
removeNode(nodeToRemove);
}
}
makeInsertedContentRoundTrippableWithHTMLTreeBuilder(insertedNodes);
removeRedundantStylesAndKeepStyleSpanInline(insertedNodes);
if (m_sanitizeFragment)
applyCommandToComposite(SimplifyMarkupCommand::create(document(), insertedNodes.firstNodeInserted(), insertedNodes.pastLastLeaf()));
m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
VisiblePosition startOfParagraphToMove = positionAtStartOfInsertedContent();
VisiblePosition destination = startOfParagraphToMove.previous();
Node* destinationNode = destination.deepEquivalent().deprecatedNode();
if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
insertNodeBefore(createBreakElement(document()), refNode.get());
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
if (!startOfParagraphToMove.deepEquivalent().inDocument())
return;
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent().downstream();
if (m_endOfInsertedContent.isOrphan())
m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent().upstream();
}
Position lastPositionToSelect;
if (fragment.hasInterchangeNewlineAtEnd()) {
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
if (!isStartOfParagraph(endOfInsertedContent)) {
setEndingSelection(endOfInsertedContent);
Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
if (isListItem(enclosingNode)) {
RefPtr<Node> newListItem = createListItemElement(document());
insertNodeAfter(newListItem, enclosingNode);
setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.get())));
} else {
insertParagraphSeparator(true, !startIsInsideMailBlockquote && highestEnclosingNodeOfType(endOfInsertedContent.deepEquivalent(),
isMailBlockquote, CannotCrossEditingBoundary, insertedNodes.firstNodeInserted()->parentNode()));
}
lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
updateNodesInserted(lastPositionToSelect.deprecatedNode());
}
} else {
lastPositionToSelect = next.deepEquivalent().downstream();
}
} else
mergeEndIfNeeded();
if (Node* mailBlockquote = enclosingNodeOfType(positionAtStartOfInsertedContent().deepEquivalent(), isMailPasteAsQuotationNode))
removeNodeAttribute(toElement(mailBlockquote), classAttr);
if (shouldPerformSmartReplace())
addSpacesForSmartReplace();
if (plainTextFragment)
m_matchStyle = false;
completeHTMLReplacement(lastPositionToSelect);
}
bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
{
if (!endBR || !endBR->inDocument())
return false;
VisiblePosition visiblePos(positionBeforeNode(endBR));
if (visiblePos.previous() == originalVisPosBeforeEndBR)
return false;
if (!document().inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
return true;
return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
}
bool ReplaceSelectionCommand::shouldPerformSmartReplace() const
{
if (!m_smartReplace)
return false;
Element* textControl = enclosingTextFormControl(positionAtStartOfInsertedContent().deepEquivalent());
if (isHTMLInputElement(textControl) && toHTMLInputElement(textControl)->isPasswordField())
return false;
return true;
}
static bool isCharacterSmartReplaceExemptConsideringNonBreakingSpace(UChar32 character, bool previousCharacter)
{
return isCharacterSmartReplaceExempt(character == noBreakSpace ? ' ' : character, previousCharacter);
}
void ReplaceSelectionCommand::addSpacesForSmartReplace()
{
VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
Position endUpstream = endOfInsertedContent.deepEquivalent().upstream();
Node* endNode = endUpstream.computeNodeBeforePosition();
int endOffset = endNode && endNode->isTextNode() ? toText(endNode)->length() : 0;
if (endUpstream.anchorType() == Position::PositionIsOffsetInAnchor) {
endNode = endUpstream.containerNode();
endOffset = endUpstream.offsetInContainerNode();
}
bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(endOfInsertedContent.characterAfter(), false);
if (needsTrailingSpace && endNode) {
bool collapseWhiteSpace = !endNode->renderer() || endNode->renderer()->style()->collapseWhiteSpace();
if (endNode->isTextNode()) {
insertTextIntoNode(toText(endNode), endOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
if (m_endOfInsertedContent.containerNode() == endNode)
m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
} else {
RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
insertNodeAfter(node, endNode);
updateNodesInserted(node.get());
}
}
document().updateLayout();
Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
Node* startNode = startDownstream.computeNodeAfterPosition();
unsigned startOffset = 0;
if (startDownstream.anchorType() == Position::PositionIsOffsetInAnchor) {
startNode = startDownstream.containerNode();
startOffset = startDownstream.offsetInContainerNode();
}
bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(startOfInsertedContent.previous().characterAfter(), true);
if (needsLeadingSpace && startNode) {
bool collapseWhiteSpace = !startNode->renderer() || startNode->renderer()->style()->collapseWhiteSpace();
if (startNode->isTextNode()) {
insertTextIntoNode(toText(startNode), startOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
} else {
RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
insertNodeBefore(node, startNode);
m_startOfInsertedContent = firstPositionInNode(node.get());
}
}
}
void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
{
Position start = positionAtStartOfInsertedContent().deepEquivalent();
Position end = positionAtEndOfInsertedContent().deepEquivalent();
if (start.isNotNull() && !start.isOrphan() && end.isNotNull() && !end.isOrphan()) {
rebalanceWhitespaceAt(start);
rebalanceWhitespaceAt(end);
if (m_matchStyle) {
ASSERT(m_insertionStyle);
applyStyle(m_insertionStyle.get(), start, end);
}
if (lastPositionToSelect.isNotNull())
end = lastPositionToSelect;
mergeTextNodesAroundPosition(start, end);
} else if (lastPositionToSelect.isNotNull())
start = end = lastPositionToSelect;
else
return;
if (m_selectReplacement)
setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
else
setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
}
void ReplaceSelectionCommand::mergeTextNodesAroundPosition(Position& position, Position& positionOnlyToBeUpdated)
{
bool positionIsOffsetInAnchor = position.anchorType() == Position::PositionIsOffsetInAnchor;
bool positionOnlyToBeUpdatedIsOffsetInAnchor = positionOnlyToBeUpdated.anchorType() == Position::PositionIsOffsetInAnchor;
RefPtr<Text> text = nullptr;
if (positionIsOffsetInAnchor && position.containerNode() && position.containerNode()->isTextNode())
text = toText(position.containerNode());
else {
Node* before = position.computeNodeBeforePosition();
if (before && before->isTextNode())
text = toText(before);
else {
Node* after = position.computeNodeAfterPosition();
if (after && after->isTextNode())
text = toText(after);
}
}
if (!text)
return;
if (text->previousSibling() && text->previousSibling()->isTextNode()) {
RefPtr<Text> previous = toText(text->previousSibling());
insertTextIntoNode(text, 0, previous->data());
if (positionIsOffsetInAnchor)
position.moveToOffset(previous->length() + position.offsetInContainerNode());
else
updatePositionForNodeRemoval(position, *previous);
if (positionOnlyToBeUpdatedIsOffsetInAnchor) {
if (positionOnlyToBeUpdated.containerNode() == text)
positionOnlyToBeUpdated.moveToOffset(previous->length() + positionOnlyToBeUpdated.offsetInContainerNode());
else if (positionOnlyToBeUpdated.containerNode() == previous)
positionOnlyToBeUpdated.moveToPosition(text, positionOnlyToBeUpdated.offsetInContainerNode());
} else {
updatePositionForNodeRemoval(positionOnlyToBeUpdated, *previous);
}
removeNode(previous);
}
if (text->nextSibling() && text->nextSibling()->isTextNode()) {
RefPtr<Text> next = toText(text->nextSibling());
unsigned originalLength = text->length();
insertTextIntoNode(text, originalLength, next->data());
if (!positionIsOffsetInAnchor)
updatePositionForNodeRemoval(position, *next);
if (positionOnlyToBeUpdatedIsOffsetInAnchor && positionOnlyToBeUpdated.containerNode() == next)
positionOnlyToBeUpdated.moveToPosition(text, originalLength + positionOnlyToBeUpdated.offsetInContainerNode());
else
updatePositionForNodeRemoval(positionOnlyToBeUpdated, *next);
removeNode(next);
}
}
EditAction ReplaceSelectionCommand::editingAction() const
{
return m_editAction;
}
Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<HTMLElement> prpListElement, Node* insertionBlock, const Position& insertPos, InsertedNodes& insertedNodes)
{
RefPtr<HTMLElement> listElement = prpListElement;
while (listElement->hasChildren() && isListElement(listElement->firstChild()) && listElement->hasOneChild())
listElement = toHTMLElement(listElement->firstChild());
bool isStart = isStartOfParagraph(VisiblePosition(insertPos));
bool isEnd = isEndOfParagraph(VisiblePosition(insertPos));
bool isMiddle = !isStart && !isEnd;
Node* lastNode = insertionBlock;
if (isMiddle) {
int textNodeOffset = insertPos.offsetInContainerNode();
if (insertPos.deprecatedNode()->isTextNode() && textNodeOffset > 0)
splitTextNode(toText(insertPos.deprecatedNode()), textNodeOffset);
splitTreeToNode(insertPos.deprecatedNode(), lastNode, true);
}
while (RefPtr<Node> listItem = listElement->firstChild()) {
listElement->removeChild(listItem.get(), ASSERT_NO_EXCEPTION);
if (isStart || isMiddle) {
insertNodeBefore(listItem, lastNode);
insertedNodes.respondToNodeInsertion(*listItem);
} else if (isEnd) {
insertNodeAfter(listItem, lastNode);
insertedNodes.respondToNodeInsertion(*listItem);
lastNode = listItem.get();
} else
ASSERT_NOT_REACHED();
}
if (isStart || isMiddle) {
if (Node* node = lastNode->previousSibling())
return node;
}
return lastNode;
}
void ReplaceSelectionCommand::updateNodesInserted(Node *node)
{
if (!node)
return;
if (m_startOfInsertedContent.isNull())
m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
m_endOfInsertedContent = lastPositionInOrAfterNode(&node->lastDescendant());
}
bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
{
if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
return false;
if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
return false;
if (nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(endingSelection().start()))
return false;
RefPtr<Node> nodeAfterInsertionPos = endingSelection().end().downstream().anchorNode();
Text* textNode = toText(fragment.firstChild());
Position start = endingSelection().start();
Position end = replaceSelectedTextInNode(textNode->data());
if (end.isNull())
return false;
if (nodeAfterInsertionPos && nodeAfterInsertionPos->parentNode() && isHTMLBRElement(*nodeAfterInsertionPos)
&& shouldRemoveEndBR(nodeAfterInsertionPos.get(), VisiblePosition(positionBeforeNode(nodeAfterInsertionPos.get()))))
removeNodeAndPruneAncestors(nodeAfterInsertionPos.get());
VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
setEndingSelection(selectionAfterReplace);
return true;
}
}