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