Home | History | Annotate | Download | only in editing
      1 /*
      2  * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
      3  * Copyright (C) 2009, 2010, 2011 Google Inc. All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  *
     14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
     15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     25  */
     26 
     27 #include "config.h"
     28 #include "core/editing/ReplaceSelectionCommand.h"
     29 
     30 #include "CSSPropertyNames.h"
     31 #include "HTMLNames.h"
     32 #include "bindings/v8/ExceptionStatePlaceholder.h"
     33 #include "core/css/CSSStyleDeclaration.h"
     34 #include "core/css/StylePropertySet.h"
     35 #include "core/dom/Document.h"
     36 #include "core/dom/DocumentFragment.h"
     37 #include "core/dom/Element.h"
     38 #include "core/dom/Text.h"
     39 #include "core/editing/ApplyStyleCommand.h"
     40 #include "core/editing/BreakBlockquoteCommand.h"
     41 #include "core/editing/FrameSelection.h"
     42 #include "core/editing/HTMLInterchange.h"
     43 #include "core/editing/SimplifyMarkupCommand.h"
     44 #include "core/editing/SmartReplace.h"
     45 #include "core/editing/TextIterator.h"
     46 #include "core/editing/VisibleUnits.h"
     47 #include "core/editing/htmlediting.h"
     48 #include "core/editing/markup.h"
     49 #include "core/events/BeforeTextInsertedEvent.h"
     50 #include "core/events/ThreadLocalEventNames.h"
     51 #include "core/html/HTMLElement.h"
     52 #include "core/html/HTMLInputElement.h"
     53 #include "core/html/HTMLTitleElement.h"
     54 #include "core/frame/Frame.h"
     55 #include "core/rendering/RenderObject.h"
     56 #include "core/rendering/RenderText.h"
     57 #include "wtf/StdLibExtras.h"
     58 #include "wtf/Vector.h"
     59 
     60 namespace WebCore {
     61 
     62 using namespace HTMLNames;
     63 
     64 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
     65 
     66 // --- ReplacementFragment helper class
     67 
     68 class ReplacementFragment {
     69     WTF_MAKE_NONCOPYABLE(ReplacementFragment);
     70 public:
     71     ReplacementFragment(Document*, DocumentFragment*, const VisibleSelection&);
     72 
     73     Node* firstChild() const;
     74     Node* lastChild() const;
     75 
     76     bool isEmpty() const;
     77 
     78     bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
     79     bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
     80 
     81     void removeNode(PassRefPtr<Node>);
     82     void removeNodePreservingChildren(PassRefPtr<Node>);
     83 
     84 private:
     85     PassRefPtr<Element> insertFragmentForTestRendering(Node* rootEditableNode);
     86     void removeUnrenderedNodes(Node*);
     87     void restoreAndRemoveTestRenderingNodesToFragment(Element*);
     88     void removeInterchangeNodes(Node*);
     89 
     90     void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
     91 
     92     RefPtr<Document> m_document;
     93     RefPtr<DocumentFragment> m_fragment;
     94     bool m_hasInterchangeNewlineAtStart;
     95     bool m_hasInterchangeNewlineAtEnd;
     96 };
     97 
     98 static bool isInterchangeNewlineNode(const Node *node)
     99 {
    100     DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
    101     return node && node->hasTagName(brTag) && toElement(node)->getAttribute(classAttr) == interchangeNewlineClassString;
    102 }
    103 
    104 static bool isInterchangeConvertedSpaceSpan(const Node *node)
    105 {
    106     DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
    107     return node->isHTMLElement() && toHTMLElement(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
    108 }
    109 
    110 static Position positionAvoidingPrecedingNodes(Position pos)
    111 {
    112     // If we're already on a break, it's probably a placeholder and we shouldn't change our position.
    113     if (editingIgnoresContent(pos.deprecatedNode()))
    114         return pos;
    115 
    116     // We also stop when changing block flow elements because even though the visual position is the
    117     // same.  E.g.,
    118     //   <div>foo^</div>^
    119     // The two positions above are the same visual position, but we want to stay in the same block.
    120     Node* enclosingBlockNode = enclosingBlock(pos.containerNode());
    121     for (Position nextPosition = pos; nextPosition.containerNode() != enclosingBlockNode; pos = nextPosition) {
    122         if (lineBreakExistsAtPosition(pos))
    123             break;
    124 
    125         if (pos.containerNode()->nonShadowBoundaryParentNode())
    126             nextPosition = positionInParentAfterNode(pos.containerNode());
    127 
    128         if (nextPosition == pos
    129             || enclosingBlock(nextPosition.containerNode()) != enclosingBlockNode
    130             || VisiblePosition(pos) != VisiblePosition(nextPosition))
    131             break;
    132     }
    133     return pos;
    134 }
    135 
    136 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, const VisibleSelection& selection)
    137     : m_document(document),
    138       m_fragment(fragment),
    139       m_hasInterchangeNewlineAtStart(false),
    140       m_hasInterchangeNewlineAtEnd(false)
    141 {
    142     if (!m_document)
    143         return;
    144     if (!m_fragment)
    145         return;
    146     if (!m_fragment->firstChild())
    147         return;
    148 
    149     RefPtr<Element> editableRoot = selection.rootEditableElement();
    150     ASSERT(editableRoot);
    151     if (!editableRoot)
    152         return;
    153 
    154     Node* shadowAncestorNode = editableRoot->deprecatedShadowAncestorNode();
    155 
    156     if (!editableRoot->getAttributeEventListener(EventTypeNames::webkitBeforeTextInserted) &&
    157         // FIXME: Remove these checks once textareas and textfields actually register an event handler.
    158         !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
    159         editableRoot->rendererIsRichlyEditable()) {
    160         removeInterchangeNodes(m_fragment.get());
    161         return;
    162     }
    163 
    164     RefPtr<Element> holder = insertFragmentForTestRendering(editableRoot.get());
    165     if (!holder) {
    166         removeInterchangeNodes(m_fragment.get());
    167         return;
    168     }
    169 
    170     RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
    171     String text = plainText(range.get(), static_cast<TextIteratorBehavior>(TextIteratorEmitsOriginalText | TextIteratorIgnoresStyleVisibility));
    172 
    173     removeInterchangeNodes(holder.get());
    174     removeUnrenderedNodes(holder.get());
    175     restoreAndRemoveTestRenderingNodesToFragment(holder.get());
    176 
    177     // Give the root a chance to change the text.
    178     RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
    179     editableRoot->dispatchEvent(evt, ASSERT_NO_EXCEPTION);
    180     if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
    181         restoreAndRemoveTestRenderingNodesToFragment(holder.get());
    182 
    183         m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
    184         if (!m_fragment->firstChild())
    185             return;
    186 
    187         holder = insertFragmentForTestRendering(editableRoot.get());
    188         removeInterchangeNodes(holder.get());
    189         removeUnrenderedNodes(holder.get());
    190         restoreAndRemoveTestRenderingNodesToFragment(holder.get());
    191     }
    192 }
    193 
    194 bool ReplacementFragment::isEmpty() const
    195 {
    196     return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
    197 }
    198 
    199 Node *ReplacementFragment::firstChild() const
    200 {
    201     return m_fragment ? m_fragment->firstChild() : 0;
    202 }
    203 
    204 Node *ReplacementFragment::lastChild() const
    205 {
    206     return m_fragment ? m_fragment->lastChild() : 0;
    207 }
    208 
    209 void ReplacementFragment::removeNodePreservingChildren(PassRefPtr<Node> node)
    210 {
    211     if (!node)
    212         return;
    213 
    214     while (RefPtr<Node> n = node->firstChild()) {
    215         removeNode(n);
    216         insertNodeBefore(n.release(), node.get());
    217     }
    218     removeNode(node);
    219 }
    220 
    221 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
    222 {
    223     if (!node)
    224         return;
    225 
    226     ContainerNode* parent = node->nonShadowBoundaryParentNode();
    227     if (!parent)
    228         return;
    229 
    230     parent->removeChild(node.get());
    231 }
    232 
    233 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
    234 {
    235     if (!node || !refNode)
    236         return;
    237 
    238     ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
    239     if (!parent)
    240         return;
    241 
    242     parent->insertBefore(node, refNode);
    243 }
    244 
    245 PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
    246 {
    247     ASSERT(m_document);
    248     RefPtr<Element> holder = createDefaultParagraphElement(*m_document.get());
    249 
    250     holder->appendChild(m_fragment);
    251     rootEditableElement->appendChild(holder.get());
    252     m_document->updateLayoutIgnorePendingStylesheets();
    253 
    254     return holder.release();
    255 }
    256 
    257 void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(Element* holder)
    258 {
    259     if (!holder)
    260         return;
    261 
    262     while (RefPtr<Node> node = holder->firstChild()) {
    263         holder->removeChild(node.get());
    264         m_fragment->appendChild(node.get());
    265     }
    266 
    267     removeNode(holder);
    268 }
    269 
    270 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
    271 {
    272     Vector<RefPtr<Node> > unrendered;
    273 
    274     for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder))
    275         if (!isNodeRendered(node) && !isTableStructureNode(node))
    276             unrendered.append(node);
    277 
    278     size_t n = unrendered.size();
    279     for (size_t i = 0; i < n; ++i)
    280         removeNode(unrendered[i]);
    281 }
    282 
    283 void ReplacementFragment::removeInterchangeNodes(Node* container)
    284 {
    285     m_hasInterchangeNewlineAtStart = false;
    286     m_hasInterchangeNewlineAtEnd = false;
    287 
    288     // Interchange newlines at the "start" of the incoming fragment must be
    289     // either the first node in the fragment or the first leaf in the fragment.
    290     Node* node = container->firstChild();
    291     while (node) {
    292         if (isInterchangeNewlineNode(node)) {
    293             m_hasInterchangeNewlineAtStart = true;
    294             removeNode(node);
    295             break;
    296         }
    297         node = node->firstChild();
    298     }
    299     if (!container->hasChildNodes())
    300         return;
    301     // Interchange newlines at the "end" of the incoming fragment must be
    302     // either the last node in the fragment or the last leaf in the fragment.
    303     node = container->lastChild();
    304     while (node) {
    305         if (isInterchangeNewlineNode(node)) {
    306             m_hasInterchangeNewlineAtEnd = true;
    307             removeNode(node);
    308             break;
    309         }
    310         node = node->lastChild();
    311     }
    312 
    313     node = container->firstChild();
    314     while (node) {
    315         RefPtr<Node> next = NodeTraversal::next(*node);
    316         if (isInterchangeConvertedSpaceSpan(node)) {
    317             next = NodeTraversal::nextSkippingChildren(*node);
    318             removeNodePreservingChildren(node);
    319         }
    320         node = next.get();
    321     }
    322 }
    323 
    324 inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node& node)
    325 {
    326     if (!m_firstNodeInserted)
    327         m_firstNodeInserted = &node;
    328 
    329     m_lastNodeInserted = &node;
    330 }
    331 
    332 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node& node)
    333 {
    334     if (m_firstNodeInserted == node)
    335         m_firstNodeInserted = NodeTraversal::next(node);
    336     if (m_lastNodeInserted == node)
    337         m_lastNodeInserted = node.lastChild() ? node.lastChild() : NodeTraversal::nextSkippingChildren(node);
    338 }
    339 
    340 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node& node)
    341 {
    342     if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
    343         m_firstNodeInserted = 0;
    344         m_lastNodeInserted = 0;
    345     } else if (m_firstNodeInserted == node) {
    346         m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
    347     } else if (m_lastNodeInserted == node) {
    348         m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
    349     }
    350 }
    351 
    352 inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node& node, Node& newNode)
    353 {
    354     if (m_firstNodeInserted == node)
    355         m_firstNodeInserted = &newNode;
    356     if (m_lastNodeInserted == node)
    357         m_lastNodeInserted = &newNode;
    358 }
    359 
    360 ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
    361     : CompositeEditCommand(document)
    362     , m_selectReplacement(options & SelectReplacement)
    363     , m_smartReplace(options & SmartReplace)
    364     , m_matchStyle(options & MatchStyle)
    365     , m_documentFragment(fragment)
    366     , m_preventNesting(options & PreventNesting)
    367     , m_movingParagraph(options & MovingParagraph)
    368     , m_editAction(editAction)
    369     , m_sanitizeFragment(options & SanitizeFragment)
    370     , m_shouldMergeEnd(false)
    371 {
    372 }
    373 
    374 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
    375 {
    376     Position existing = endOfExistingContent.deepEquivalent();
    377     Position inserted = endOfInsertedContent.deepEquivalent();
    378     bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
    379     return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
    380 }
    381 
    382 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
    383 {
    384     if (m_movingParagraph)
    385         return false;
    386 
    387     VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
    388     VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
    389     if (prev.isNull())
    390         return false;
    391 
    392     // When we have matching quote levels, its ok to merge more frequently.
    393     // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
    394     // And we should only merge here if the selection start was inside a mail blockquote.  This prevents against removing a
    395     // blockquote from newly pasted quoted content that was pasted into an unquoted position.  If that unquoted position happens
    396     // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
    397     if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
    398         return true;
    399 
    400     return !selectionStartWasStartOfParagraph
    401         && !fragmentHasInterchangeNewlineAtStart
    402         && isStartOfParagraph(startOfInsertedContent)
    403         && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
    404         && shouldMerge(startOfInsertedContent, prev);
    405 }
    406 
    407 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
    408 {
    409     VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
    410     VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
    411     if (next.isNull())
    412         return false;
    413 
    414     return !selectionEndWasEndOfParagraph
    415         && isEndOfParagraph(endOfInsertedContent)
    416         && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
    417         && shouldMerge(endOfInsertedContent, next);
    418 }
    419 
    420 static bool isMailPasteAsQuotationNode(const Node* node)
    421 {
    422     return node && node->hasTagName(blockquoteTag) && node->isElementNode() && toElement(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
    423 }
    424 
    425 static bool isHeaderElement(const Node* a)
    426 {
    427     if (!a)
    428         return false;
    429 
    430     return a->hasTagName(h1Tag)
    431         || a->hasTagName(h2Tag)
    432         || a->hasTagName(h3Tag)
    433         || a->hasTagName(h4Tag)
    434         || a->hasTagName(h5Tag)
    435         || a->hasTagName(h6Tag);
    436 }
    437 
    438 static bool haveSameTagName(Node* a, Node* b)
    439 {
    440     return a && b && a->isElementNode() && b->isElementNode() && toElement(a)->tagName() == toElement(b)->tagName();
    441 }
    442 
    443 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
    444 {
    445     if (source.isNull() || destination.isNull())
    446         return false;
    447 
    448     Node* sourceNode = source.deepEquivalent().deprecatedNode();
    449     Node* destinationNode = destination.deepEquivalent().deprecatedNode();
    450     Node* sourceBlock = enclosingBlock(sourceNode);
    451     Node* destinationBlock = enclosingBlock(destinationNode);
    452     return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
    453            sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock))  &&
    454            enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
    455            enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
    456            (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
    457            // Don't merge to or from a position before or after a block because it would
    458            // be a no-op and cause infinite recursion.
    459            !isBlock(sourceNode) && !isBlock(destinationNode);
    460 }
    461 
    462 // Style rules that match just inserted elements could change their appearance, like
    463 // a div inserted into a document with div { display:inline; }.
    464 void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
    465 {
    466     RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
    467     RefPtr<Node> next;
    468     for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
    469         // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
    470 
    471         next = NodeTraversal::next(*node);
    472         if (!node->isStyledElement())
    473             continue;
    474 
    475         Element* element = toElement(node);
    476 
    477         const StylePropertySet* inlineStyle = element->inlineStyle();
    478         RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
    479         if (inlineStyle) {
    480             if (element->isHTMLElement()) {
    481                 Vector<QualifiedName> attributes;
    482                 HTMLElement* htmlElement = toHTMLElement(element);
    483                 ASSERT(htmlElement);
    484 
    485                 if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
    486                     // e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
    487                     node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
    488                     element = toElement(node);
    489                     insertedNodes.didReplaceNode(*htmlElement, *node);
    490                 } else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
    491                     EditingStyle::DoNotExtractMatchingStyle)) {
    492                     // e.g. <font size="3" style="font-size: 20px;"> is converted to <font style="font-size: 20px;">
    493                     for (size_t i = 0; i < attributes.size(); i++)
    494                         removeNodeAttribute(element, attributes[i]);
    495                 }
    496             }
    497 
    498             ContainerNode* context = element->parentNode();
    499 
    500             // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
    501             // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
    502             Node* blockquoteNode = !context || isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
    503             if (blockquoteNode)
    504                 newInlineStyle->removeStyleFromRulesAndContext(element, document().documentElement());
    505 
    506             newInlineStyle->removeStyleFromRulesAndContext(element, context);
    507         }
    508 
    509         if (!inlineStyle || newInlineStyle->isEmpty()) {
    510             if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
    511                 insertedNodes.willRemoveNodePreservingChildren(*element);
    512                 removeNodePreservingChildren(element);
    513                 continue;
    514             }
    515             removeNodeAttribute(element, styleAttr);
    516         } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount()) {
    517             setNodeAttribute(element, styleAttr, AtomicString(newInlineStyle->style()->asText()));
    518         }
    519 
    520         // FIXME: Tolerate differences in id, class, and style attributes.
    521         if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
    522             && VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
    523             && VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
    524             insertedNodes.willRemoveNodePreservingChildren(*element);
    525             removeNodePreservingChildren(element);
    526             continue;
    527         }
    528 
    529         if (element->parentNode() && element->parentNode()->rendererIsRichlyEditable())
    530             removeNodeAttribute(element, contenteditableAttr);
    531 
    532         // WebKit used to not add display: inline and float: none on copy.
    533         // Keep this code around for backward compatibility
    534         if (isLegacyAppleStyleSpan(element)) {
    535             if (!element->firstChild()) {
    536                 insertedNodes.willRemoveNodePreservingChildren(*element);
    537                 removeNodePreservingChildren(element);
    538                 continue;
    539             }
    540             // There are other styles that style rules can give to style spans,
    541             // but these are the two important ones because they'll prevent
    542             // inserted content from appearing in the right paragraph.
    543             // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
    544             // results. We already know one issue because td elements ignore their display property
    545             // in quirks mode (which Mail.app is always in). We should look for an alternative.
    546 
    547             // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
    548             if (isBlock(element))
    549                 element->style()->setPropertyInternal(CSSPropertyDisplay, "inline", false, IGNORE_EXCEPTION);
    550             if (element->renderer() && element->renderer()->style()->isFloating())
    551                 element->style()->setPropertyInternal(CSSPropertyFloat, "none", false, IGNORE_EXCEPTION);
    552         }
    553     }
    554 }
    555 
    556 static bool isProhibitedParagraphChild(const AtomicString& name)
    557 {
    558     // https://dvcs.w3.org/hg/editing/raw-file/57abe6d3cb60/editing.html#prohibited-paragraph-child
    559     DEFINE_STATIC_LOCAL(HashSet<AtomicString>, elements, ());
    560     if (elements.isEmpty()) {
    561         elements.add(addressTag.localName());
    562         elements.add(articleTag.localName());
    563         elements.add(asideTag.localName());
    564         elements.add(blockquoteTag.localName());
    565         elements.add(captionTag.localName());
    566         elements.add(centerTag.localName());
    567         elements.add(colTag.localName());
    568         elements.add(colgroupTag.localName());
    569         elements.add(ddTag.localName());
    570         elements.add(detailsTag.localName());
    571         elements.add(dirTag.localName());
    572         elements.add(divTag.localName());
    573         elements.add(dlTag.localName());
    574         elements.add(dtTag.localName());
    575         elements.add(fieldsetTag.localName());
    576         elements.add(figcaptionTag.localName());
    577         elements.add(figureTag.localName());
    578         elements.add(footerTag.localName());
    579         elements.add(formTag.localName());
    580         elements.add(h1Tag.localName());
    581         elements.add(h2Tag.localName());
    582         elements.add(h3Tag.localName());
    583         elements.add(h4Tag.localName());
    584         elements.add(h5Tag.localName());
    585         elements.add(h6Tag.localName());
    586         elements.add(headerTag.localName());
    587         elements.add(hgroupTag.localName());
    588         elements.add(hrTag.localName());
    589         elements.add(liTag.localName());
    590         elements.add(listingTag.localName());
    591         elements.add(mainTag.localName()); // Missing in the specification.
    592         elements.add(menuTag.localName());
    593         elements.add(navTag.localName());
    594         elements.add(olTag.localName());
    595         elements.add(pTag.localName());
    596         elements.add(plaintextTag.localName());
    597         elements.add(preTag.localName());
    598         elements.add(sectionTag.localName());
    599         elements.add(summaryTag.localName());
    600         elements.add(tableTag.localName());
    601         elements.add(tbodyTag.localName());
    602         elements.add(tdTag.localName());
    603         elements.add(tfootTag.localName());
    604         elements.add(thTag.localName());
    605         elements.add(theadTag.localName());
    606         elements.add(trTag.localName());
    607         elements.add(ulTag.localName());
    608         elements.add(xmpTag.localName());
    609     }
    610     return elements.contains(name);
    611 }
    612 
    613 void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
    614 {
    615     RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
    616     RefPtr<Node> next;
    617     for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
    618         next = NodeTraversal::next(*node);
    619 
    620         if (!node->isHTMLElement())
    621             continue;
    622 
    623         if (isProhibitedParagraphChild(toHTMLElement(node)->localName())) {
    624             if (HTMLElement* paragraphElement = toHTMLElement(enclosingNodeWithTag(positionInParentBeforeNode(node.get()), pTag)))
    625                 moveNodeOutOfAncestor(node, paragraphElement);
    626         }
    627 
    628         if (isHeaderElement(node.get())) {
    629             if (HTMLElement* headerElement = toHTMLElement(highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement)))
    630                 moveNodeOutOfAncestor(node, headerElement);
    631         }
    632     }
    633 }
    634 
    635 void ReplaceSelectionCommand::moveNodeOutOfAncestor(PassRefPtr<Node> prpNode, PassRefPtr<Node> prpAncestor)
    636 {
    637     RefPtr<Node> node = prpNode;
    638     RefPtr<Node> ancestor = prpAncestor;
    639 
    640     if (!ancestor->parentNode()->rendererIsEditable())
    641         return;
    642 
    643     VisiblePosition positionAtEndOfNode = lastPositionInOrAfterNode(node.get());
    644     VisiblePosition lastPositionInParagraph = lastPositionInNode(ancestor.get());
    645     if (positionAtEndOfNode == lastPositionInParagraph) {
    646         removeNode(node);
    647         if (ancestor->nextSibling())
    648             insertNodeBefore(node, ancestor->nextSibling());
    649         else
    650             appendNode(node, ancestor->parentNode());
    651     } else {
    652         RefPtr<Node> nodeToSplitTo = splitTreeToNode(node.get(), ancestor.get(), true);
    653         removeNode(node);
    654         insertNodeBefore(node, nodeToSplitTo);
    655     }
    656     if (!ancestor->firstChild())
    657         removeNode(ancestor.release());
    658 }
    659 
    660 static inline bool nodeHasVisibleRenderText(Text& text)
    661 {
    662     return text.renderer() && toRenderText(text.renderer())->renderedTextLength() > 0;
    663 }
    664 
    665 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
    666 {
    667     document().updateLayoutIgnorePendingStylesheets();
    668 
    669     Node& lastLeafInserted = insertedNodes.lastLeafInserted();
    670     if (lastLeafInserted.isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
    671         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), selectTag)
    672         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), scriptTag)) {
    673         insertedNodes.willRemoveNode(lastLeafInserted);
    674         removeNode(&lastLeafInserted);
    675     }
    676 
    677     // We don't have to make sure that firstNodeInserted isn't inside a select or script element, because
    678     // it is a top level node in the fragment and the user can't insert into those elements.
    679     Node* firstNodeInserted = insertedNodes.firstNodeInserted();
    680     if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*firstNodeInserted))) {
    681         insertedNodes.willRemoveNode(*firstNodeInserted);
    682         removeNode(firstNodeInserted);
    683     }
    684 }
    685 
    686 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
    687 {
    688     // FIXME: Why is this hack here?  What's special about <select> tags?
    689     Node* enclosingSelect = enclosingNodeWithTag(m_endOfInsertedContent, selectTag);
    690     return enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent;
    691 }
    692 
    693 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
    694 {
    695     return m_startOfInsertedContent;
    696 }
    697 
    698 static void removeHeadContents(ReplacementFragment& fragment)
    699 {
    700     Node* next = 0;
    701     for (Node* node = fragment.firstChild(); node; node = next) {
    702         if (node->hasTagName(baseTag)
    703             || node->hasTagName(linkTag)
    704             || node->hasTagName(metaTag)
    705             || node->hasTagName(styleTag)
    706             || isHTMLTitleElement(node)) {
    707             next = NodeTraversal::nextSkippingChildren(*node);
    708             fragment.removeNode(node);
    709         } else {
    710             next = NodeTraversal::next(*node);
    711         }
    712     }
    713 }
    714 
    715 // Remove style spans before insertion if they are unnecessary.  It's faster because we'll
    716 // avoid doing a layout.
    717 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
    718 {
    719     Node* topNode = fragment.firstChild();
    720 
    721     // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
    722     // and doesn't receive the optimization.
    723     if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
    724         return false;
    725 
    726     // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
    727     // before inserting it.  Look for and handle style spans after insertion.
    728     if (!isLegacyAppleStyleSpan(topNode))
    729         return false;
    730 
    731     Node* wrappingStyleSpan = topNode;
    732     RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
    733     String styleText = styleAtInsertionPos->style()->asText();
    734 
    735     // FIXME: This string comparison is a naive way of comparing two styles.
    736     // We should be taking the diff and check that the diff is empty.
    737     if (styleText != toElement(wrappingStyleSpan)->getAttribute(styleAttr))
    738         return false;
    739 
    740     fragment.removeNodePreservingChildren(wrappingStyleSpan);
    741     return true;
    742 }
    743 
    744 // At copy time, WebKit wraps copied content in a span that contains the source document's
    745 // default styles.  If the copied Range inherits any other styles from its ancestors, we put
    746 // those styles on a second span.
    747 // This function removes redundant styles from those spans, and removes the spans if all their
    748 // styles are redundant.
    749 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
    750 // We should remove styles from spans that are overridden by all of their children, either here
    751 // or at copy time.
    752 void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
    753 {
    754     HTMLElement* wrappingStyleSpan = 0;
    755     // The style span that contains the source document's default style should be at
    756     // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
    757     // so search for the top level style span instead of assuming it's at the top.
    758     for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
    759         if (isLegacyAppleStyleSpan(node)) {
    760             wrappingStyleSpan = toHTMLElement(node);
    761             break;
    762         }
    763     }
    764 
    765     // There might not be any style spans if we're pasting from another application or if
    766     // we are here because of a document.execCommand("InsertHTML", ...) call.
    767     if (!wrappingStyleSpan)
    768         return;
    769 
    770     RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->inlineStyle());
    771     ContainerNode* context = wrappingStyleSpan->parentNode();
    772 
    773     // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
    774     // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
    775     Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
    776     if (blockquoteNode)
    777         context = document().documentElement();
    778 
    779     // This operation requires that only editing styles to be removed from sourceDocumentStyle.
    780     style->prepareToApplyAt(firstPositionInNode(context));
    781 
    782     // Remove block properties in the span's style. This prevents properties that probably have no effect
    783     // currently from affecting blocks later if the style is cloned for a new block element during a future
    784     // editing operation.
    785     // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
    786     // with block styles by the editing engine used to style them.  WebKit doesn't do this, but others might.
    787     style->removeBlockProperties();
    788 
    789     if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
    790         insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
    791         removeNodePreservingChildren(wrappingStyleSpan);
    792     } else {
    793         setNodeAttribute(wrappingStyleSpan, styleAttr, AtomicString(style->style()->asText()));
    794     }
    795 }
    796 
    797 void ReplaceSelectionCommand::mergeEndIfNeeded()
    798 {
    799     if (!m_shouldMergeEnd)
    800         return;
    801 
    802     VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
    803     VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
    804 
    805     // Bail to avoid infinite recursion.
    806     if (m_movingParagraph) {
    807         ASSERT_NOT_REACHED();
    808         return;
    809     }
    810 
    811     // Merging two paragraphs will destroy the moved one's block styles.  Always move the end of inserted forward
    812     // to preserve the block style of the paragraph already in the document, unless the paragraph to move would
    813     // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
    814     // block styles.
    815     bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
    816 
    817     VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
    818     VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
    819 
    820     // Merging forward could result in deleting the destination anchor node.
    821     // To avoid this, we add a placeholder node before the start of the paragraph.
    822     if (endOfParagraph(startOfParagraphToMove) == destination) {
    823         RefPtr<Node> placeholder = createBreakElement(document());
    824         insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
    825         destination = VisiblePosition(positionBeforeNode(placeholder.get()));
    826     }
    827 
    828     moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
    829 
    830     // Merging forward will remove m_endOfInsertedContent from the document.
    831     if (mergeForward) {
    832         if (m_startOfInsertedContent.isOrphan())
    833             m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
    834          m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
    835         // If we merged text nodes, m_endOfInsertedContent could be null. If this is the case, we use m_startOfInsertedContent.
    836         if (m_endOfInsertedContent.isNull())
    837             m_endOfInsertedContent = m_startOfInsertedContent;
    838     }
    839 }
    840 
    841 static Node* enclosingInline(Node* node)
    842 {
    843     while (ContainerNode* parent = node->parentNode()) {
    844         if (parent->isBlockFlowElement() || parent->hasTagName(bodyTag))
    845             return node;
    846         // Stop if any previous sibling is a block.
    847         for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
    848             if (sibling->isBlockFlowElement())
    849                 return node;
    850         }
    851         node = parent;
    852     }
    853     return node;
    854 }
    855 
    856 static bool isInlineNodeWithStyle(const Node* node)
    857 {
    858     // We don't want to skip over any block elements.
    859     if (isBlock(node))
    860         return false;
    861 
    862     if (!node->isHTMLElement())
    863         return false;
    864 
    865     // We can skip over elements whose class attribute is
    866     // one of our internal classes.
    867     const HTMLElement* element = toHTMLElement(node);
    868     const AtomicString& classAttributeValue = element->getAttribute(classAttr);
    869     if (classAttributeValue == AppleTabSpanClass
    870         || classAttributeValue == AppleConvertedSpace
    871         || classAttributeValue == ApplePasteAsQuotation)
    872         return true;
    873 
    874     return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
    875 }
    876 
    877 inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
    878 {
    879     Node* containgBlock = enclosingBlock(insertionPos.containerNode());
    880     return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
    881 }
    882 
    883 void ReplaceSelectionCommand::doApply()
    884 {
    885     VisibleSelection selection = endingSelection();
    886     ASSERT(selection.isCaretOrRange());
    887     ASSERT(selection.start().deprecatedNode());
    888     if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
    889         return;
    890 
    891     if (!selection.rootEditableElement())
    892         return;
    893 
    894     ReplacementFragment fragment(&document(), m_documentFragment.get(), selection);
    895     if (performTrivialReplace(fragment))
    896         return;
    897 
    898     // We can skip matching the style if the selection is plain text.
    899     if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
    900         && (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
    901         m_matchStyle = false;
    902 
    903     if (m_matchStyle) {
    904         m_insertionStyle = EditingStyle::create(selection.start());
    905         m_insertionStyle->mergeTypingStyle(&document());
    906     }
    907 
    908     VisiblePosition visibleStart = selection.visibleStart();
    909     VisiblePosition visibleEnd = selection.visibleEnd();
    910 
    911     bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
    912     bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
    913 
    914     Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
    915 
    916     Position insertionPos = selection.start();
    917     bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
    918     bool selectionIsPlainText = !selection.isContentRichlyEditable();
    919     Element* currentRoot = selection.rootEditableElement();
    920 
    921     if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
    922         startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
    923         m_preventNesting = false;
    924 
    925     if (selection.isRange()) {
    926         // When the end of the selection being pasted into is at the end of a paragraph, and that selection
    927         // spans multiple blocks, not merging may leave an empty line.
    928         // When the start of the selection being pasted into is at the start of a block, not merging
    929         // will leave hanging block(s).
    930         // Merge blocks if the start of the selection was in a Mail blockquote, since we handle
    931         // that case specially to prevent nesting.
    932         bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
    933         // FIXME: We should only expand to include fully selected special elements if we are copying a
    934         // selection and pasting it on top of itself.
    935         deleteSelection(false, mergeBlocksAfterDelete, true, false);
    936         visibleStart = endingSelection().visibleStart();
    937         if (fragment.hasInterchangeNewlineAtStart()) {
    938             if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
    939                 if (!isEndOfEditableOrNonEditableContent(visibleStart))
    940                     setEndingSelection(visibleStart.next());
    941             } else
    942                 insertParagraphSeparator();
    943         }
    944         insertionPos = endingSelection().start();
    945     } else {
    946         ASSERT(selection.isCaret());
    947         if (fragment.hasInterchangeNewlineAtStart()) {
    948             VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
    949             if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
    950                 setEndingSelection(next);
    951             else  {
    952                 insertParagraphSeparator();
    953                 visibleStart = endingSelection().visibleStart();
    954             }
    955         }
    956         // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
    957         // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
    958         // As long as the  div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
    959         // not <div>xbar<div>bar</div><div>bazx</div></div>.
    960         // Don't do this if the selection started in a Mail blockquote.
    961         if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
    962             insertParagraphSeparator();
    963             setEndingSelection(endingSelection().visibleStart().previous());
    964         }
    965         insertionPos = endingSelection().start();
    966     }
    967 
    968     // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
    969     // out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case
    970     // breaking the blockquote will prevent the content from actually being inserted in the table.
    971     if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
    972         applyCommandToComposite(BreakBlockquoteCommand::create(document()));
    973         // This will leave a br between the split.
    974         Node* br = endingSelection().start().deprecatedNode();
    975         ASSERT(br->hasTagName(brTag));
    976         // Insert content between the two blockquotes, but remove the br (since it was just a placeholder).
    977         insertionPos = positionInParentBeforeNode(br);
    978         removeNode(br);
    979     }
    980 
    981     // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
    982     prepareWhitespaceAtPositionForSplit(insertionPos);
    983 
    984     // If the downstream node has been removed there's no point in continuing.
    985     if (!insertionPos.downstream().deprecatedNode())
    986       return;
    987 
    988     // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
    989     // p that maps to the same visible position as p (since in the case where a br is at the end of a block and collapsed
    990     // away, there are positions after the br which map to the same visible position as [br, 0]).
    991     Node* endBR = insertionPos.downstream().deprecatedNode()->hasTagName(brTag) ? insertionPos.downstream().deprecatedNode() : 0;
    992     VisiblePosition originalVisPosBeforeEndBR;
    993     if (endBR)
    994         originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
    995 
    996     RefPtr<Node> insertionBlock = enclosingBlock(insertionPos.deprecatedNode());
    997 
    998     // Adjust insertionPos to prevent nesting.
    999     // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
   1000     if (m_preventNesting && insertionBlock && !isTableCell(insertionBlock.get()) && !startIsInsideMailBlockquote) {
   1001         ASSERT(insertionBlock != currentRoot);
   1002         VisiblePosition visibleInsertionPos(insertionPos);
   1003         if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
   1004             insertionPos = positionInParentAfterNode(insertionBlock.get());
   1005         else if (isStartOfBlock(visibleInsertionPos))
   1006             insertionPos = positionInParentBeforeNode(insertionBlock.get());
   1007     }
   1008 
   1009     // Paste at start or end of link goes outside of link.
   1010     insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
   1011 
   1012     // FIXME: Can this wait until after the operation has been performed?  There doesn't seem to be
   1013     // any work performed after this that queries or uses the typing style.
   1014     if (Frame* frame = document().frame())
   1015         frame->selection().clearTypingStyle();
   1016 
   1017     removeHeadContents(fragment);
   1018 
   1019     // We don't want the destination to end up inside nodes that weren't selected.  To avoid that, we move the
   1020     // position forward without changing the visible position so we're still at the same visible location, but
   1021     // outside of preceding tags.
   1022     insertionPos = positionAvoidingPrecedingNodes(insertionPos);
   1023 
   1024     // Paste into run of tabs splits the tab span.
   1025     insertionPos = positionOutsideTabSpan(insertionPos);
   1026 
   1027     bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
   1028 
   1029     // We're finished if there is nothing to add.
   1030     if (fragment.isEmpty() || !fragment.firstChild())
   1031         return;
   1032 
   1033     // If we are not trying to match the destination style we prefer a position
   1034     // that is outside inline elements that provide style.
   1035     // This way we can produce a less verbose markup.
   1036     // We can skip this optimization for fragments not wrapped in one of
   1037     // our style spans and for positions inside list items
   1038     // since insertAsListItems already does the right thing.
   1039     if (!m_matchStyle && !enclosingList(insertionPos.containerNode())) {
   1040         if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
   1041             splitTextNode(insertionPos.containerText(), insertionPos.offsetInContainerNode());
   1042             insertionPos = firstPositionInNode(insertionPos.containerNode());
   1043         }
   1044 
   1045         if (RefPtr<Node> nodeToSplitTo = nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(insertionPos)) {
   1046             if (insertionPos.containerNode() != nodeToSplitTo->parentNode()) {
   1047                 Node* splitStart = insertionPos.computeNodeAfterPosition();
   1048                 if (!splitStart)
   1049                     splitStart = insertionPos.containerNode();
   1050                 nodeToSplitTo = splitTreeToNode(splitStart, nodeToSplitTo->parentNode()).get();
   1051                 insertionPos = positionInParentBeforeNode(nodeToSplitTo.get());
   1052             }
   1053         }
   1054     }
   1055 
   1056     // FIXME: When pasting rich content we're often prevented from heading down the fast path by style spans.  Try
   1057     // again here if they've been removed.
   1058 
   1059     // 1) Insert the content.
   1060     // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>.
   1061     // 3) Merge the start of the added content with the content before the position being pasted into.
   1062     // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
   1063     // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
   1064     // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
   1065     // incoming fragment.
   1066     // 5) Add spaces for smart replace.
   1067     // 6) Select the replacement if requested, and match style if requested.
   1068 
   1069     InsertedNodes insertedNodes;
   1070     RefPtr<Node> refNode = fragment.firstChild();
   1071     ASSERT(refNode);
   1072     RefPtr<Node> node = refNode->nextSibling();
   1073 
   1074     fragment.removeNode(refNode);
   1075 
   1076     Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
   1077     if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
   1078         && blockStart && blockStart->renderer()->isListItem())
   1079         refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
   1080     else {
   1081         insertNodeAt(refNode, insertionPos);
   1082         insertedNodes.respondToNodeInsertion(*refNode);
   1083     }
   1084 
   1085     // Mutation events (bug 22634) may have already removed the inserted content
   1086     if (!refNode->inDocument())
   1087         return;
   1088 
   1089     bool plainTextFragment = isPlainTextMarkup(refNode.get());
   1090 
   1091     while (node) {
   1092         RefPtr<Node> next = node->nextSibling();
   1093         fragment.removeNode(node.get());
   1094         insertNodeAfter(node, refNode);
   1095         insertedNodes.respondToNodeInsertion(*node);
   1096 
   1097         // Mutation events (bug 22634) may have already removed the inserted content
   1098         if (!node->inDocument())
   1099             return;
   1100 
   1101         refNode = node;
   1102         if (node && plainTextFragment)
   1103             plainTextFragment = isPlainTextMarkup(node.get());
   1104         node = next;
   1105     }
   1106 
   1107     removeUnrenderedTextNodesAtEnds(insertedNodes);
   1108 
   1109     if (!handledStyleSpans)
   1110         handleStyleSpans(insertedNodes);
   1111 
   1112     // Mutation events (bug 20161) may have already removed the inserted content
   1113     if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
   1114         return;
   1115 
   1116     // Scripts specified in javascript protocol may remove |insertionBlock|
   1117     // during insertion, e.g. <iframe src="javascript:...">
   1118     if (insertionBlock && !insertionBlock->inDocument())
   1119         insertionBlock = 0;
   1120 
   1121     VisiblePosition startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
   1122 
   1123     // We inserted before the insertionBlock to prevent nesting, and the content before the insertionBlock wasn't in its own block and
   1124     // didn't have a br after it, so the inserted content ended up in the same paragraph.
   1125     if (insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
   1126         insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
   1127 
   1128     if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) {
   1129         RefPtr<Node> parent = endBR->parentNode();
   1130         insertedNodes.willRemoveNode(*endBR);
   1131         removeNode(endBR);
   1132         if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
   1133             insertedNodes.willRemoveNode(*nodeToRemove);
   1134             removeNode(nodeToRemove);
   1135         }
   1136     }
   1137 
   1138     makeInsertedContentRoundTrippableWithHTMLTreeBuilder(insertedNodes);
   1139 
   1140     removeRedundantStylesAndKeepStyleSpanInline(insertedNodes);
   1141 
   1142     if (m_sanitizeFragment)
   1143         applyCommandToComposite(SimplifyMarkupCommand::create(document(), insertedNodes.firstNodeInserted(), insertedNodes.pastLastLeaf()));
   1144 
   1145     // Setup m_startOfInsertedContent and m_endOfInsertedContent. This should be the last two lines of code that access insertedNodes.
   1146     m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
   1147     m_endOfInsertedContent = lastPositionInOrAfterNode(&insertedNodes.lastLeafInserted());
   1148 
   1149     // Determine whether or not we should merge the end of inserted content with what's after it before we do
   1150     // the start merge so that the start merge doesn't effect our decision.
   1151     m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
   1152 
   1153     if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
   1154         VisiblePosition startOfParagraphToMove = positionAtStartOfInsertedContent();
   1155         VisiblePosition destination = startOfParagraphToMove.previous();
   1156         // We need to handle the case where we need to merge the end
   1157         // but our destination node is inside an inline that is the last in the block.
   1158         // We insert a placeholder before the newly inserted content to avoid being merged into the inline.
   1159         Node* destinationNode = destination.deepEquivalent().deprecatedNode();
   1160         if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
   1161             insertNodeBefore(createBreakElement(document()), refNode.get());
   1162 
   1163         // Merging the the first paragraph of inserted content with the content that came
   1164         // before the selection that was pasted into would also move content after
   1165         // the selection that was pasted into if: only one paragraph was being pasted,
   1166         // and it was not wrapped in a block, the selection that was pasted into ended
   1167         // at the end of a block and the next paragraph didn't start at the start of a block.
   1168         // Insert a line break just after the inserted content to separate it from what
   1169         // comes after and prevent that from happening.
   1170         VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
   1171         if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
   1172             insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
   1173             // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
   1174             if (!startOfParagraphToMove.deepEquivalent().inDocument())
   1175                 return;
   1176         }
   1177 
   1178         // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes.  The nodes are
   1179         // only ever used to create positions where inserted content starts/ends.
   1180         moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
   1181         m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent().downstream();
   1182         if (m_endOfInsertedContent.isOrphan())
   1183             m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent().upstream();
   1184     }
   1185 
   1186     Position lastPositionToSelect;
   1187     if (fragment.hasInterchangeNewlineAtEnd()) {
   1188         VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
   1189         VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
   1190 
   1191         if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
   1192             if (!isStartOfParagraph(endOfInsertedContent)) {
   1193                 setEndingSelection(endOfInsertedContent);
   1194                 Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
   1195                 if (isListItem(enclosingNode)) {
   1196                     RefPtr<Node> newListItem = createListItemElement(document());
   1197                     insertNodeAfter(newListItem, enclosingNode);
   1198                     setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.get())));
   1199                 } else {
   1200                     // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph
   1201                     // block's style seems to annoy users.
   1202                     insertParagraphSeparator(true, !startIsInsideMailBlockquote && highestEnclosingNodeOfType(endOfInsertedContent.deepEquivalent(),
   1203                         isMailBlockquote, CannotCrossEditingBoundary, insertedNodes.firstNodeInserted()->parentNode()));
   1204                 }
   1205 
   1206                 // Select up to the paragraph separator that was added.
   1207                 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
   1208                 updateNodesInserted(lastPositionToSelect.deprecatedNode());
   1209             }
   1210         } else {
   1211             // Select up to the beginning of the next paragraph.
   1212             lastPositionToSelect = next.deepEquivalent().downstream();
   1213         }
   1214 
   1215     } else
   1216         mergeEndIfNeeded();
   1217 
   1218     if (Node* mailBlockquote = enclosingNodeOfType(positionAtStartOfInsertedContent().deepEquivalent(), isMailPasteAsQuotationNode))
   1219         removeNodeAttribute(toElement(mailBlockquote), classAttr);
   1220 
   1221     if (shouldPerformSmartReplace())
   1222         addSpacesForSmartReplace();
   1223 
   1224     // If we are dealing with a fragment created from plain text
   1225     // no style matching is necessary.
   1226     if (plainTextFragment)
   1227         m_matchStyle = false;
   1228 
   1229     completeHTMLReplacement(lastPositionToSelect);
   1230 }
   1231 
   1232 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
   1233 {
   1234     if (!endBR || !endBR->inDocument())
   1235         return false;
   1236 
   1237     VisiblePosition visiblePos(positionBeforeNode(endBR));
   1238 
   1239     // Don't remove the br if nothing was inserted.
   1240     if (visiblePos.previous() == originalVisPosBeforeEndBR)
   1241         return false;
   1242 
   1243     // Remove the br if it is collapsed away and so is unnecessary.
   1244     if (!document().inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
   1245         return true;
   1246 
   1247     // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
   1248     // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
   1249     return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
   1250 }
   1251 
   1252 bool ReplaceSelectionCommand::shouldPerformSmartReplace() const
   1253 {
   1254     if (!m_smartReplace)
   1255         return false;
   1256 
   1257     Element* textControl = enclosingTextFormControl(positionAtStartOfInsertedContent().deepEquivalent());
   1258     if (textControl && textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isPasswordField())
   1259         return false; // Disable smart replace for password fields.
   1260 
   1261     return true;
   1262 }
   1263 
   1264 static bool isCharacterSmartReplaceExemptConsideringNonBreakingSpace(UChar32 character, bool previousCharacter)
   1265 {
   1266     return isCharacterSmartReplaceExempt(character == noBreakSpace ? ' ' : character, previousCharacter);
   1267 }
   1268 
   1269 void ReplaceSelectionCommand::addSpacesForSmartReplace()
   1270 {
   1271     VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
   1272     VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
   1273 
   1274     Position endUpstream = endOfInsertedContent.deepEquivalent().upstream();
   1275     Node* endNode = endUpstream.computeNodeBeforePosition();
   1276     int endOffset = endNode && endNode->isTextNode() ? toText(endNode)->length() : 0;
   1277     if (endUpstream.anchorType() == Position::PositionIsOffsetInAnchor) {
   1278         endNode = endUpstream.containerNode();
   1279         endOffset = endUpstream.offsetInContainerNode();
   1280     }
   1281 
   1282     bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(endOfInsertedContent.characterAfter(), false);
   1283     if (needsTrailingSpace && endNode) {
   1284         bool collapseWhiteSpace = !endNode->renderer() || endNode->renderer()->style()->collapseWhiteSpace();
   1285         if (endNode->isTextNode()) {
   1286             insertTextIntoNode(toText(endNode), endOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
   1287             if (m_endOfInsertedContent.containerNode() == endNode)
   1288                 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
   1289         } else {
   1290             RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
   1291             insertNodeAfter(node, endNode);
   1292             updateNodesInserted(node.get());
   1293         }
   1294     }
   1295 
   1296     document().updateLayout();
   1297 
   1298     Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
   1299     Node* startNode = startDownstream.computeNodeAfterPosition();
   1300     unsigned startOffset = 0;
   1301     if (startDownstream.anchorType() == Position::PositionIsOffsetInAnchor) {
   1302         startNode = startDownstream.containerNode();
   1303         startOffset = startDownstream.offsetInContainerNode();
   1304     }
   1305 
   1306     bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(startOfInsertedContent.previous().characterAfter(), true);
   1307     if (needsLeadingSpace && startNode) {
   1308         bool collapseWhiteSpace = !startNode->renderer() || startNode->renderer()->style()->collapseWhiteSpace();
   1309         if (startNode->isTextNode()) {
   1310             insertTextIntoNode(toText(startNode), startOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
   1311             if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
   1312                 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
   1313         } else {
   1314             RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
   1315             // Don't updateNodesInserted. Doing so would set m_endOfInsertedContent to be the node containing the leading space,
   1316             // but m_endOfInsertedContent is supposed to mark the end of pasted content.
   1317             insertNodeBefore(node, startNode);
   1318             m_startOfInsertedContent = firstPositionInNode(node.get());
   1319         }
   1320     }
   1321 }
   1322 
   1323 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
   1324 {
   1325     Position start = positionAtStartOfInsertedContent().deepEquivalent();
   1326     Position end = positionAtEndOfInsertedContent().deepEquivalent();
   1327 
   1328     // Mutation events may have deleted start or end
   1329     if (start.isNotNull() && !start.isOrphan() && end.isNotNull() && !end.isOrphan()) {
   1330         // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
   1331         rebalanceWhitespaceAt(start);
   1332         rebalanceWhitespaceAt(end);
   1333 
   1334         if (m_matchStyle) {
   1335             ASSERT(m_insertionStyle);
   1336             applyStyle(m_insertionStyle.get(), start, end);
   1337         }
   1338 
   1339         if (lastPositionToSelect.isNotNull())
   1340             end = lastPositionToSelect;
   1341 
   1342         mergeTextNodesAroundPosition(start, end);
   1343     } else if (lastPositionToSelect.isNotNull())
   1344         start = end = lastPositionToSelect;
   1345     else
   1346         return;
   1347 
   1348     if (m_selectReplacement)
   1349         setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
   1350     else
   1351         setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
   1352 }
   1353 
   1354 void ReplaceSelectionCommand::mergeTextNodesAroundPosition(Position& position, Position& positionOnlyToBeUpdated)
   1355 {
   1356     bool positionIsOffsetInAnchor = position.anchorType() == Position::PositionIsOffsetInAnchor;
   1357     bool positionOnlyToBeUpdatedIsOffsetInAnchor = positionOnlyToBeUpdated.anchorType() == Position::PositionIsOffsetInAnchor;
   1358     RefPtr<Text> text = 0;
   1359     if (positionIsOffsetInAnchor && position.containerNode() && position.containerNode()->isTextNode())
   1360         text = toText(position.containerNode());
   1361     else {
   1362         Node* before = position.computeNodeBeforePosition();
   1363         if (before && before->isTextNode())
   1364             text = toText(before);
   1365         else {
   1366             Node* after = position.computeNodeAfterPosition();
   1367             if (after && after->isTextNode())
   1368                 text = toText(after);
   1369         }
   1370     }
   1371     if (!text)
   1372         return;
   1373 
   1374     if (text->previousSibling() && text->previousSibling()->isTextNode()) {
   1375         RefPtr<Text> previous = toText(text->previousSibling());
   1376         insertTextIntoNode(text, 0, previous->data());
   1377 
   1378         if (positionIsOffsetInAnchor)
   1379             position.moveToOffset(previous->length() + position.offsetInContainerNode());
   1380         else
   1381             updatePositionForNodeRemoval(position, previous.get());
   1382 
   1383         if (positionOnlyToBeUpdatedIsOffsetInAnchor) {
   1384             if (positionOnlyToBeUpdated.containerNode() == text)
   1385                 positionOnlyToBeUpdated.moveToOffset(previous->length() + positionOnlyToBeUpdated.offsetInContainerNode());
   1386             else if (positionOnlyToBeUpdated.containerNode() == previous)
   1387                 positionOnlyToBeUpdated.moveToPosition(text, positionOnlyToBeUpdated.offsetInContainerNode());
   1388         } else
   1389             updatePositionForNodeRemoval(positionOnlyToBeUpdated, previous.get());
   1390 
   1391         removeNode(previous);
   1392     }
   1393     if (text->nextSibling() && text->nextSibling()->isTextNode()) {
   1394         RefPtr<Text> next = toText(text->nextSibling());
   1395         unsigned originalLength = text->length();
   1396         insertTextIntoNode(text, originalLength, next->data());
   1397 
   1398         if (!positionIsOffsetInAnchor)
   1399             updatePositionForNodeRemoval(position, next.get());
   1400 
   1401         if (positionOnlyToBeUpdatedIsOffsetInAnchor && positionOnlyToBeUpdated.containerNode() == next)
   1402             positionOnlyToBeUpdated.moveToPosition(text, originalLength + positionOnlyToBeUpdated.offsetInContainerNode());
   1403         else
   1404             updatePositionForNodeRemoval(positionOnlyToBeUpdated, next.get());
   1405 
   1406         removeNode(next);
   1407     }
   1408 }
   1409 
   1410 EditAction ReplaceSelectionCommand::editingAction() const
   1411 {
   1412     return m_editAction;
   1413 }
   1414 
   1415 // If the user is inserting a list into an existing list, instead of nesting the list,
   1416 // we put the list items into the existing list.
   1417 Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<HTMLElement> prpListElement, Node* insertionBlock, const Position& insertPos, InsertedNodes& insertedNodes)
   1418 {
   1419     RefPtr<HTMLElement> listElement = prpListElement;
   1420 
   1421     while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1)
   1422         listElement = toHTMLElement(listElement->firstChild());
   1423 
   1424     bool isStart = isStartOfParagraph(insertPos);
   1425     bool isEnd = isEndOfParagraph(insertPos);
   1426     bool isMiddle = !isStart && !isEnd;
   1427     Node* lastNode = insertionBlock;
   1428 
   1429     // If we're in the middle of a list item, we should split it into two separate
   1430     // list items and insert these nodes between them.
   1431     if (isMiddle) {
   1432         int textNodeOffset = insertPos.offsetInContainerNode();
   1433         if (insertPos.deprecatedNode()->isTextNode() && textNodeOffset > 0)
   1434             splitTextNode(toText(insertPos.deprecatedNode()), textNodeOffset);
   1435         splitTreeToNode(insertPos.deprecatedNode(), lastNode, true);
   1436     }
   1437 
   1438     while (RefPtr<Node> listItem = listElement->firstChild()) {
   1439         listElement->removeChild(listItem.get(), ASSERT_NO_EXCEPTION);
   1440         if (isStart || isMiddle) {
   1441             insertNodeBefore(listItem, lastNode);
   1442             insertedNodes.respondToNodeInsertion(*listItem);
   1443         } else if (isEnd) {
   1444             insertNodeAfter(listItem, lastNode);
   1445             insertedNodes.respondToNodeInsertion(*listItem);
   1446             lastNode = listItem.get();
   1447         } else
   1448             ASSERT_NOT_REACHED();
   1449     }
   1450     if (isStart || isMiddle)
   1451         lastNode = lastNode->previousSibling();
   1452     return lastNode;
   1453 }
   1454 
   1455 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
   1456 {
   1457     if (!node)
   1458         return;
   1459 
   1460     if (m_startOfInsertedContent.isNull())
   1461         m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
   1462 
   1463     m_endOfInsertedContent = lastPositionInOrAfterNode(&node->lastDescendant());
   1464 }
   1465 
   1466 // During simple pastes, where we're just pasting a text node into a run of text, we insert the text node
   1467 // directly into the text node that holds the selection.  This is much faster than the generalized code in
   1468 // ReplaceSelectionCommand, and works around <https://bugs.webkit.org/show_bug.cgi?id=6148> since we don't
   1469 // split text nodes.
   1470 bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
   1471 {
   1472     if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
   1473         return false;
   1474 
   1475     // FIXME: Would be nice to handle smart replace in the fast path.
   1476     if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
   1477         return false;
   1478 
   1479     // e.g. when "bar" is inserted after "foo" in <div><u>foo</u></div>, "bar" should not be underlined.
   1480     if (nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(endingSelection().start()))
   1481         return false;
   1482 
   1483     RefPtr<Node> nodeAfterInsertionPos = endingSelection().end().downstream().anchorNode();
   1484     Text* textNode = toText(fragment.firstChild());
   1485     // Our fragment creation code handles tabs, spaces, and newlines, so we don't have to worry about those here.
   1486 
   1487     Position start = endingSelection().start();
   1488     Position end = replaceSelectedTextInNode(textNode->data());
   1489     if (end.isNull())
   1490         return false;
   1491 
   1492     if (nodeAfterInsertionPos && nodeAfterInsertionPos->parentNode() && nodeAfterInsertionPos->hasTagName(brTag)
   1493         && shouldRemoveEndBR(nodeAfterInsertionPos.get(), positionBeforeNode(nodeAfterInsertionPos.get())))
   1494         removeNodeAndPruneAncestors(nodeAfterInsertionPos.get());
   1495 
   1496     VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
   1497 
   1498     setEndingSelection(selectionAfterReplace);
   1499 
   1500     return true;
   1501 }
   1502 
   1503 } // namespace WebCore
   1504