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