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