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