ReplaceSelectionCommand.cpp 60.1 KB
Newer Older
mjs's avatar
mjs committed
1
/*
darin@apple.com's avatar
darin@apple.com committed
2
 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
mjs's avatar
mjs committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

mjs's avatar
mjs committed
26
#include "config.h"
darin's avatar
darin committed
27
#include "ReplaceSelectionCommand.h"
mjs's avatar
mjs committed
28

darin's avatar
darin committed
29
#include "ApplyStyleCommand.h"
darin's avatar
darin committed
30
#include "BeforeTextInsertedEvent.h"
darin@apple.com's avatar
darin@apple.com committed
31
#include "BreakBlockquoteCommand.h"
darin's avatar
darin committed
32
#include "CSSComputedStyleDeclaration.h"
darin@apple.com's avatar
darin@apple.com committed
33
#include "CSSMutableStyleDeclaration.h"
darin's avatar
darin committed
34
#include "CSSPropertyNames.h"
justing's avatar
justing committed
35
#include "CSSValueKeywords.h"
darin's avatar
darin committed
36
#include "Document.h"
darin's avatar
darin committed
37
#include "DocumentFragment.h"
darin's avatar
darin committed
38
#include "EditingText.h"
darin's avatar
darin committed
39
#include "Element.h"
darin@apple.com's avatar
darin@apple.com committed
40
#include "EventNames.h"
darin's avatar
darin committed
41
#include "Frame.h"
42
#include "FrameSelection.h"
darin's avatar
darin committed
43
#include "HTMLElement.h"
adele's avatar
adele committed
44
#include "HTMLInputElement.h"
darin@apple.com's avatar
darin@apple.com committed
45
#include "HTMLInterchange.h"
darin's avatar
darin committed
46
#include "HTMLNames.h"
47
#include "NodeList.h"
48
#include "RenderObject.h"
aliceli1's avatar
aliceli1 committed
49
#include "SmartReplace.h"
darin's avatar
darin committed
50
#include "TextIterator.h"
darin's avatar
darin committed
51 52 53
#include "htmlediting.h"
#include "markup.h"
#include "visible_units.h"
54
#include <wtf/StdLibExtras.h>
55
#include <wtf/Vector.h>
mjs's avatar
mjs committed
56

darin's avatar
darin committed
57
namespace WebCore {
mjs's avatar
mjs committed
58

59 60
typedef Vector<RefPtr<Node> > NodeVector;

darin's avatar
darin committed
61
using namespace HTMLNames;
mjs's avatar
mjs committed
62

darin@apple.com's avatar
darin@apple.com committed
63 64 65 66
enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };

// --- ReplacementFragment helper class

67 68
class ReplacementFragment {
    WTF_MAKE_NONCOPYABLE(ReplacementFragment);
darin@apple.com's avatar
darin@apple.com committed
69
public:
70
    ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&);
darin@apple.com's avatar
darin@apple.com committed
71 72 73 74 75 76 77 78 79 80 81 82 83

    Node* firstChild() const;
    Node* lastChild() const;

    bool isEmpty() const;
    
    bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
    bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
    
    void removeNode(PassRefPtr<Node>);
    void removeNodePreservingChildren(Node*);

private:
84
    PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* context);
darin@apple.com's avatar
darin@apple.com committed
85
    void removeUnrenderedNodes(Node*);
86
    void restoreTestRenderingNodesToFragment(StyledElement*);
darin@apple.com's avatar
darin@apple.com committed
87 88
    void removeInterchangeNodes(Node*);
    
eric@webkit.org's avatar
eric@webkit.org committed
89
    void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
darin@apple.com's avatar
darin@apple.com committed
90 91 92 93 94 95 96 97

    RefPtr<Document> m_document;
    RefPtr<DocumentFragment> m_fragment;
    bool m_matchStyle;
    bool m_hasInterchangeNewlineAtStart;
    bool m_hasInterchangeNewlineAtEnd;
};

justing's avatar
justing committed
98 99
static bool isInterchangeNewlineNode(const Node *node)
{
100
    DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
justing's avatar
justing committed
101 102 103 104 105 106
    return node && node->hasTagName(brTag) && 
           static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
}

static bool isInterchangeConvertedSpaceSpan(const Node *node)
{
107
    DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
justing's avatar
justing committed
108 109 110 111
    return node->isHTMLElement() && 
           static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
}

112 113 114
static Position positionAvoidingPrecedingNodes(Position pos)
{
    // 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 117 118 119 120 121
        return pos;

    // We also stop when changing block flow elements because even though the visual position is the
    // same.  E.g.,
    //   <div>foo^</div>^
    // The two positions above are the same visual position, but we want to stay in the same block.
122 123
    Node* stopNode = pos.deprecatedNode()->enclosingBlockFlowElement();
    while (stopNode != pos.deprecatedNode() && VisiblePosition(pos) == VisiblePosition(pos.next()))
124 125 126 127
        pos = pos.next();
    return pos;
}

128
ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const VisibleSelection& selection)
justing's avatar
justing committed
129
    : m_document(document),
justing's avatar
justing committed
130
      m_fragment(fragment),
mjs's avatar
mjs committed
131 132
      m_matchStyle(matchStyle), 
      m_hasInterchangeNewlineAtStart(false), 
justing's avatar
justing committed
133
      m_hasInterchangeNewlineAtEnd(false)
mjs's avatar
mjs committed
134 135 136
{
    if (!m_document)
        return;
darin's avatar
darin committed
137
    if (!m_fragment)
mjs's avatar
mjs committed
138
        return;
justing's avatar
justing committed
139
    if (!m_fragment->firstChild())
mjs's avatar
mjs committed
140
        return;
justing's avatar
justing committed
141
    
darin's avatar
darin committed
142
    Element* editableRoot = selection.rootEditableElement();
justing's avatar
justing committed
143 144 145
    ASSERT(editableRoot);
    if (!editableRoot)
        return;
justing's avatar
justing committed
146
    
adele's avatar
adele committed
147
    Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
justing's avatar
justing committed
148
    
149
    if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
justing's avatar
justing committed
150
        // FIXME: Remove these checks once textareas and textfields actually register an event handler.
151
        !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
152
        editableRoot->rendererIsRichlyEditable()) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
153
        removeInterchangeNodes(m_fragment.get());
justing's avatar
justing committed
154 155
        return;
    }
darin's avatar
darin committed
156

157
    Node* styleNode = selection.base().deprecatedNode();
158
    RefPtr<StyledElement> holder = insertFragmentForTestRendering(styleNode);
justing's avatar
justing committed
159
    
160
    RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
justing's avatar
justing committed
161 162
    String text = plainText(range.get());
    // Give the root a chance to change the text.
darin@apple.com's avatar
darin@apple.com committed
163
    RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
justing's avatar
justing committed
164
    ExceptionCode ec = 0;
ap@webkit.org's avatar
ap@webkit.org committed
165
    editableRoot->dispatchEvent(evt, ec);
justing's avatar
justing committed
166
    ASSERT(ec == 0);
167
    if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
darin's avatar
darin committed
168
        restoreTestRenderingNodesToFragment(holder.get());
justing's avatar
justing committed
169
        removeNode(holder);
darin's avatar
darin committed
170

eric@webkit.org's avatar
eric@webkit.org committed
171
        m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
justing's avatar
justing committed
172
        if (!m_fragment->firstChild())
darin's avatar
darin committed
173 174
            return;
        holder = insertFragmentForTestRendering(styleNode);
justing's avatar
justing committed
175
    }
justing's avatar
justing committed
176
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
177
    removeInterchangeNodes(holder.get());
178
    
justing's avatar
justing committed
179 180 181
    removeUnrenderedNodes(holder.get());
    restoreTestRenderingNodesToFragment(holder.get());
    removeNode(holder);
mjs's avatar
mjs committed
182 183
}

darin's avatar
darin committed
184
bool ReplacementFragment::isEmpty() const
mjs's avatar
mjs committed
185
{
darin's avatar
darin committed
186
    return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
mjs's avatar
mjs committed
187 188
}

darin's avatar
darin committed
189
Node *ReplacementFragment::firstChild() const 
mjs's avatar
mjs committed
190
{ 
191
    return m_fragment ? m_fragment->firstChild() : 0; 
mjs's avatar
mjs committed
192 193
}

darin's avatar
darin committed
194
Node *ReplacementFragment::lastChild() const 
mjs's avatar
mjs committed
195
{ 
196
    return m_fragment ? m_fragment->lastChild() : 0; 
mjs's avatar
mjs committed
197 198
}

darin's avatar
darin committed
199
void ReplacementFragment::removeNodePreservingChildren(Node *node)
mjs's avatar
mjs committed
200 201 202 203
{
    if (!node)
        return;

darin's avatar
darin committed
204
    while (RefPtr<Node> n = node->firstChild()) {
mjs's avatar
mjs committed
205
        removeNode(n);
eric@webkit.org's avatar
eric@webkit.org committed
206
        insertNodeBefore(n.release(), node);
mjs's avatar
mjs committed
207 208 209 210
    }
    removeNode(node);
}

darin's avatar
darin committed
211
void ReplacementFragment::removeNode(PassRefPtr<Node> node)
mjs's avatar
mjs committed
212 213 214
{
    if (!node)
        return;
eseidel's avatar
eseidel committed
215
    
216
    ContainerNode* parent = node->parentNode();
mjs's avatar
mjs committed
217 218
    if (!parent)
        return;
eseidel's avatar
eseidel committed
219
    
darin's avatar
darin committed
220 221 222
    ExceptionCode ec = 0;
    parent->removeChild(node.get(), ec);
    ASSERT(ec == 0);
mjs's avatar
mjs committed
223 224
}

eric@webkit.org's avatar
eric@webkit.org committed
225
void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
mjs's avatar
mjs committed
226 227 228 229
{
    if (!node || !refNode)
        return;
        
230
    ContainerNode* parent = refNode->parentNode();
mjs's avatar
mjs committed
231 232 233
    if (!parent)
        return;
        
darin's avatar
darin committed
234 235 236
    ExceptionCode ec = 0;
    parent->insertBefore(node, refNode, ec);
    ASSERT(ec == 0);
mjs's avatar
mjs committed
237 238
}

239
PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* context)
mjs's avatar
mjs committed
240
{
241
    HTMLElement* body = m_document->body();
mjs's avatar
mjs committed
242
    if (!body)
justing's avatar
justing committed
243
        return 0;
justing's avatar
justing committed
244

245
    RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
mjs's avatar
mjs committed
246
    
darin's avatar
darin committed
247
    ExceptionCode ec = 0;
darin's avatar
darin committed
248

adele's avatar
adele committed
249
    // Copy the whitespace and user-select style from the context onto this element.
250
    // Walk up past <br> elements which may be placeholders and might have their own specified styles.
adele's avatar
adele committed
251
    // FIXME: We should examine other style properties to see if they would be appropriate to consider during the test rendering.
darin's avatar
darin committed
252
    Node* n = context;
253
    while (n && (!n->isElementNode() || n->hasTagName(brTag)))
darin's avatar
darin committed
254 255
        n = n->parentNode();
    if (n) {
darin@apple.com's avatar
darin@apple.com committed
256
        RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n);
darin's avatar
darin committed
257
        CSSStyleDeclaration* style = holder->style();
258
        style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec);
darin's avatar
darin committed
259
        ASSERT(ec == 0);
260
        style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec);
adele's avatar
adele committed
261
        ASSERT(ec == 0);
darin's avatar
darin committed
262 263
    }
    
justing's avatar
justing committed
264
    holder->appendChild(m_fragment, ec);
darin's avatar
darin committed
265
    ASSERT(ec == 0);
mjs's avatar
mjs committed
266
    
justing's avatar
justing committed
267
    body->appendChild(holder.get(), ec);
darin's avatar
darin committed
268
    ASSERT(ec == 0);
mjs's avatar
mjs committed
269
    
darin's avatar
darin committed
270
    m_document->updateLayoutIgnorePendingStylesheets();
justing's avatar
justing committed
271 272 273 274
    
    return holder.release();
}

275
void ReplacementFragment::restoreTestRenderingNodesToFragment(StyledElement* holder)
justing's avatar
justing committed
276 277 278 279 280 281 282 283 284 285 286 287 288
{
    if (!holder)
        return;
    
    ExceptionCode ec = 0;
    while (RefPtr<Node> node = holder->firstChild()) {
        holder->removeChild(node.get(), ec);
        ASSERT(ec == 0);
        m_fragment->appendChild(node.get(), ec);
        ASSERT(ec == 0);
    }
}

darin's avatar
darin committed
289
void ReplacementFragment::removeUnrenderedNodes(Node* holder)
mjs's avatar
mjs committed
290
{
darin's avatar
darin committed
291
    Vector<Node*> unrendered;
mjs's avatar
mjs committed
292

darin's avatar
darin committed
293
    for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
mjs's avatar
mjs committed
294 295 296
        if (!isNodeRendered(node) && !isTableStructureNode(node))
            unrendered.append(node);

darin's avatar
darin committed
297 298 299
    size_t n = unrendered.size();
    for (size_t i = 0; i < n; ++i)
        removeNode(unrendered[i]);
mjs's avatar
mjs committed
300 301
}

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
302
void ReplacementFragment::removeInterchangeNodes(Node* container)
justing's avatar
justing committed
303
{
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
304 305 306
    // Interchange newlines at the "start" of the incoming fragment must be
    // either the first node in the fragment or the first leaf in the fragment.
    Node* node = container->firstChild();
justing's avatar
justing committed
307 308
    while (node) {
        if (isInterchangeNewlineNode(node)) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
309 310 311
            m_hasInterchangeNewlineAtStart = true;
            removeNode(node);
            break;
justing's avatar
justing committed
312
        }
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        node = node->firstChild();
    }
    if (!container->hasChildNodes())
        return;
    // Interchange newlines at the "end" of the incoming fragment must be
    // either the last node in the fragment or the last leaf in the fragment.
    node = container->lastChild();
    while (node) {
        if (isInterchangeNewlineNode(node)) {
            m_hasInterchangeNewlineAtEnd = true;
            removeNode(node);
            break;
        }
        node = node->lastChild();
    }
    
    node = container->firstChild();
    while (node) {
        Node *next = node->traverseNextNode();
        if (isInterchangeConvertedSpaceSpan(node)) {
justing's avatar
justing committed
333 334 335
            RefPtr<Node> n = 0;
            while ((n = node->firstChild())) {
                removeNode(n);
eric@webkit.org's avatar
eric@webkit.org committed
336
                insertNodeBefore(n, node);
justing's avatar
justing committed
337 338 339 340 341 342 343 344 345
            }
            removeNode(node);
            if (n)
                next = n->traverseNextNode();
        }
        node = next;
    }
}

346 347 348 349 350 351 352 353 354 355
ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
    : CompositeEditCommand(document)
    , m_selectReplacement(options & SelectReplacement)
    , m_smartReplace(options & SmartReplace)
    , m_matchStyle(options & MatchStyle)
    , m_documentFragment(fragment)
    , m_preventNesting(options & PreventNesting)
    , m_movingParagraph(options & MovingParagraph)
    , m_editAction(editAction)
    , m_shouldMergeEnd(false)
mjs's avatar
mjs committed
356 357 358
{
}

bdakin@apple.com's avatar
bdakin@apple.com committed
359 360 361 362
static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
{
    Position existing = endOfExistingContent.deepEquivalent();
    Position inserted = endOfInsertedContent.deepEquivalent();
363
    bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
bdakin@apple.com's avatar
bdakin@apple.com committed
364 365 366
    return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
}

adele@apple.com's avatar
adele@apple.com committed
367
bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
mjs's avatar
mjs committed
368
{
adele@apple.com's avatar
adele@apple.com committed
369 370 371
    if (m_movingParagraph)
        return false;
    
justing's avatar
justing committed
372
    VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
373
    VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
justing's avatar
justing committed
374 375
    if (prev.isNull())
        return false;
bdakin@apple.com's avatar
bdakin@apple.com committed
376
    
adele@apple.com's avatar
adele@apple.com committed
377 378 379 380 381 382
    // When we have matching quote levels, its ok to merge more frequently.
    // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
    // And we should only merge here if the selection start was inside a mail blockquote.  This prevents against removing a 
    // blockquote from newly pasted quoted content that was pasted into an unquoted position.  If that unquoted position happens 
    // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
    if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
bdakin@apple.com's avatar
bdakin@apple.com committed
383 384
        return true;

385 386 387 388 389
    return !selectionStartWasStartOfParagraph
        && !fragmentHasInterchangeNewlineAtStart
        && isStartOfParagraph(startOfInsertedContent)
        && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
        && shouldMerge(startOfInsertedContent, prev);
mjs's avatar
mjs committed
390 391
}

justing's avatar
justing committed
392
bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
justing's avatar
justing committed
393
{
justing's avatar
justing committed
394
    VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
395
    VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
justing's avatar
justing committed
396
    if (next.isNull())
justing's avatar
justing committed
397 398
        return false;

399 400 401 402
    return !selectionEndWasEndOfParagraph
        && isEndOfParagraph(endOfInsertedContent)
        && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
        && shouldMerge(endOfInsertedContent, next);
justing's avatar
justing committed
403 404
}

justing's avatar
justing committed
405
static bool isMailPasteAsQuotationNode(const Node* node)
justing's avatar
justing committed
406
{
justing's avatar
justing committed
407
    return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
justing's avatar
justing committed
408 409
}

harrison's avatar
harrison committed
410
// Wrap CompositeEditCommand::removeNodePreservingChildren() so we can update the nodes we track
justing's avatar
justing committed
411 412 413 414
void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node)
{
    if (m_firstNodeInserted == node)
        m_firstNodeInserted = node->traverseNextNode();
justing's avatar
justing committed
415 416
    if (m_lastLeafInserted == node)
        m_lastLeafInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling();
justing's avatar
justing committed
417 418 419
    CompositeEditCommand::removeNodePreservingChildren(node);
}

harrison's avatar
harrison committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
// Wrap CompositeEditCommand::removeNodeAndPruneAncestors() so we can update the nodes we track
void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node)
{
    // prepare in case m_firstNodeInserted and/or m_lastLeafInserted get removed
    // FIXME: shouldn't m_lastLeafInserted be adjusted using traversePreviousNode()?
    Node* afterFirst = m_firstNodeInserted ? m_firstNodeInserted->traverseNextSibling() : 0;
    Node* afterLast = m_lastLeafInserted ? m_lastLeafInserted->traverseNextSibling() : 0;
    
    CompositeEditCommand::removeNodeAndPruneAncestors(node);
    
    // adjust m_firstNodeInserted and m_lastLeafInserted since either or both may have been removed
    if (m_lastLeafInserted && !m_lastLeafInserted->inDocument())
        m_lastLeafInserted = afterLast;
    if (m_firstNodeInserted && !m_firstNodeInserted->inDocument())
        m_firstNodeInserted = m_lastLeafInserted && m_lastLeafInserted->inDocument() ? afterFirst : 0;
}
436 437

static bool isHeaderElement(Node* a)
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
438 439 440 441 442 443 444 445 446 447 448
{
    if (!a)
        return false;
        
    return a->hasTagName(h1Tag) ||
           a->hasTagName(h2Tag) ||
           a->hasTagName(h3Tag) ||
           a->hasTagName(h4Tag) ||
           a->hasTagName(h5Tag);
}

449
static bool haveSameTagName(Node* a, Node* b)
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
450 451 452
{
    return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName();
}
harrison's avatar
harrison committed
453

bdakin@apple.com's avatar
bdakin@apple.com committed
454
bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
justing's avatar
justing committed
455
{
bdakin@apple.com's avatar
bdakin@apple.com committed
456
    if (source.isNull() || destination.isNull())
justing's avatar
justing committed
457 458
        return false;
        
459 460
    Node* sourceNode = source.deepEquivalent().deprecatedNode();
    Node* destinationNode = destination.deepEquivalent().deprecatedNode();
bdakin@apple.com's avatar
bdakin@apple.com committed
461
    Node* sourceBlock = enclosingBlock(sourceNode);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
462
    Node* destinationBlock = enclosingBlock(destinationNode);
bdakin@apple.com's avatar
bdakin@apple.com committed
463 464 465 466
    return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
           sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock))  &&
           enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
           enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
467
           (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
justing's avatar
justing committed
468 469
           // Don't merge to or from a position before or after a block because it would
           // be a no-op and cause infinite recursion.
bdakin@apple.com's avatar
bdakin@apple.com committed
470
           !isBlock(sourceNode) && !isBlock(destinationNode);
justing's avatar
justing committed
471 472
}

justing's avatar
justing committed
473 474 475 476 477 478 479
// Style rules that match just inserted elements could change their appearance, like
// a div inserted into a document with div { display:inline; }.
void ReplaceSelectionCommand::negateStyleRulesThatAffectAppearance()
{
    for (RefPtr<Node> node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
        // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
        if (isStyleSpan(node.get())) {
480
            HTMLElement* e = toHTMLElement(node.get());
justing's avatar
justing committed
481 482 483
            // There are other styles that style rules can give to style spans,
            // but these are the two important ones because they'll prevent
            // inserted content from appearing in the right paragraph.
harrison's avatar
harrison committed
484 485 486
            // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
            // results. We already know one issue because td elements ignore their display property
            // in quirks mode (which Mail.app is always in). We should look for an alternative.
justing's avatar
justing committed
487
            if (isBlock(e))
488
                e->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline);
justing's avatar
justing committed
489
            if (e->renderer() && e->renderer()->style()->floating() != FNONE)
490
                e->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone);
justing's avatar
justing committed
491 492 493 494 495 496
        }
        if (node == m_lastLeafInserted)
            break;
    }
}

justing's avatar
justing committed
497 498 499
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds()
{
    document()->updateLayoutIgnorePendingStylesheets();
500 501 502 503
    if (!m_lastLeafInserted->renderer()
        && m_lastLeafInserted->isTextNode()
        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(m_lastLeafInserted.get()), selectTag)
        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(m_lastLeafInserted.get()), scriptTag)) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
504 505 506 507 508 509 510
        if (m_firstNodeInserted == m_lastLeafInserted) {
            removeNode(m_lastLeafInserted.get());
            m_lastLeafInserted = 0;
            m_firstNodeInserted = 0;
            return;
        }
        RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode();
justing's avatar
justing committed
511 512 513 514 515 516 517 518
        removeNode(m_lastLeafInserted.get());
        m_lastLeafInserted = previous;
    }
    
    // We don't have to make sure that m_firstNodeInserted isn't inside a select or script element, because
    // it is a top level node in the fragment and the user can't insert into those elements.
    if (!m_firstNodeInserted->renderer() && 
        m_firstNodeInserted->isTextNode()) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
519 520 521 522 523 524 525
        if (m_firstNodeInserted == m_lastLeafInserted) {
            removeNode(m_firstNodeInserted.get());
            m_firstNodeInserted = 0;
            m_lastLeafInserted = 0;
            return;
        }
        RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling();
justing's avatar
justing committed
526 527 528 529 530
        removeNode(m_firstNodeInserted.get());
        m_firstNodeInserted = next;
    }
}

justing's avatar
justing committed
531 532 533 534
void ReplaceSelectionCommand::handlePasteAsQuotationNode()
{
    Node* node = m_firstNodeInserted.get();
    if (isMailPasteAsQuotationNode(node))
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
535
        removeNodeAttribute(static_cast<Element*>(node), classAttr);
justing's avatar
justing committed
536 537
}

justing's avatar
justing committed
538 539 540
VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent()
{
    Node* lastNode = m_lastLeafInserted.get();
eric@webkit.org's avatar
eric@webkit.org committed
541
    // FIXME: Why is this hack here?  What's special about <select> tags?
542
    Node* enclosingSelect = enclosingNodeWithTag(firstPositionInOrBeforeNode(lastNode), selectTag);
justing's avatar
justing committed
543 544
    if (enclosingSelect)
        lastNode = enclosingSelect;
545
    return lastPositionInOrAfterNode(lastNode);
justing's avatar
justing committed
546 547 548 549
}

VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent()
{
justing's avatar
justing committed
550
    // Return the inserted content's first VisiblePosition.
551
    return VisiblePosition(nextCandidate(positionInParentBeforeNode(m_firstNodeInserted.get())));
justing's avatar
justing committed
552 553
}

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
554 555 556 557 558
// Remove style spans before insertion if they are unnecessary.  It's faster because we'll 
// avoid doing a layout.
static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
{
    Node* topNode = fragment.firstChild();
559

adele@apple.com's avatar
adele@apple.com committed
560 561
    // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
    // and doesn't receive the optimization.
562
    if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
563
        return false;
564

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
565 566 567 568
    // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
    // before inserting it.  Look for and handle style spans after insertion.
    if (!isStyleSpan(topNode))
        return false;
569

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
570 571
    Node* sourceDocumentStyleSpan = topNode;
    RefPtr<Node> copiedRangeStyleSpan = sourceDocumentStyleSpan->firstChild();
572

573
    RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
574
    String styleText = styleAtInsertionPos->style()->cssText();
575

576 577
    // FIXME: This string comparison is a naive way of comparing two styles.
    // We should be taking the diff and check that the diff is empty.
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
578 579 580 581 582
    if (styleText == static_cast<Element*>(sourceDocumentStyleSpan)->getAttribute(styleAttr)) {
        fragment.removeNodePreservingChildren(sourceDocumentStyleSpan);
        if (!isStyleSpan(copiedRangeStyleSpan.get()))
            return true;
    }
583

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
584 585 586 587
    if (isStyleSpan(copiedRangeStyleSpan.get()) && styleText == static_cast<Element*>(copiedRangeStyleSpan.get())->getAttribute(styleAttr)) {
        fragment.removeNodePreservingChildren(copiedRangeStyleSpan.get());
        return true;
    }
588

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    return false;
}

// At copy time, WebKit wraps copied content in a span that contains the source document's 
// default styles.  If the copied Range inherits any other styles from its ancestors, we put 
// those styles on a second span.
// This function removes redundant styles from those spans, and removes the spans if all their 
// styles are redundant. 
// We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
// We should remove styles from spans that are overridden by all of their children, either here
// or at copy time.
void ReplaceSelectionCommand::handleStyleSpans()
{
    Node* sourceDocumentStyleSpan = 0;
    Node* copiedRangeStyleSpan = 0;
    // The style span that contains the source document's default style should be at
    // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
    // so search for the top level style span instead of assuming it's at the top.
    for (Node* node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
        if (isStyleSpan(node)) {
            sourceDocumentStyleSpan = node;
            // If the copied Range's common ancestor had user applied inheritable styles
            // on it, they'll be on a second style span, just below the one that holds the 
            // document defaults.
            if (isStyleSpan(node->firstChild()))
                copiedRangeStyleSpan = node->firstChild();
            break;
        }
    }
    
    // There might not be any style spans if we're pasting from another application or if 
    // we are here because of a document.execCommand("InsertHTML", ...) call.
    if (!sourceDocumentStyleSpan)
        return;
623

624
    RefPtr<EditingStyle> sourceDocumentStyle = EditingStyle::create(toHTMLElement(sourceDocumentStyleSpan)->getInlineStyleDecl());
625
    ContainerNode* context = sourceDocumentStyleSpan->parentNode();
626

adele@apple.com's avatar
adele@apple.com committed
627 628
    // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
    // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
629
    Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
adele@apple.com's avatar
adele@apple.com committed
630
    if (blockquoteNode) {
631
        sourceDocumentStyle->removeStyleConflictingWithStyleOfNode(blockquoteNode);
adele@apple.com's avatar
adele@apple.com committed
632
        context = blockquoteNode->parentNode();
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
633
    }
634 635

    // This operation requires that only editing styles to be removed from sourceDocumentStyle.
636
    sourceDocumentStyle->prepareToApplyAt(firstPositionInNode(context));
637

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
638 639 640 641 642 643
    // Remove block properties in the span's style. This prevents properties that probably have no effect 
    // currently from affecting blocks later if the style is cloned for a new block element during a future 
    // editing operation.
    // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
    // with block styles by the editing engine used to style them.  WebKit doesn't do this, but others might.
    sourceDocumentStyle->removeBlockProperties();
644

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
645 646
    // The styles on sourceDocumentStyleSpan are all redundant, and there is no copiedRangeStyleSpan
    // to consider.  We're finished.
647
    if (sourceDocumentStyle->isEmpty() && !copiedRangeStyleSpan) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
648 649 650
        removeNodePreservingChildren(sourceDocumentStyleSpan);
        return;
    }
651

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
652
    // There are non-redundant styles on sourceDocumentStyleSpan, but there is no
653 654
    // copiedRangeStyleSpan.  Remove the span, because it could be surrounding block elements,
    // and apply the styles to its children.
655 656
    if (!sourceDocumentStyle->isEmpty() && !copiedRangeStyleSpan) {
        copyStyleToChildren(sourceDocumentStyleSpan, sourceDocumentStyle->style()); 
657
        removeNodePreservingChildren(sourceDocumentStyleSpan);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
658 659 660
        return;
    }
    
661
    RefPtr<EditingStyle> copiedRangeStyle = EditingStyle::create(toHTMLElement(copiedRangeStyleSpan)->getInlineStyleDecl());
662

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
663 664
    // We're going to put sourceDocumentStyleSpan's non-redundant styles onto copiedRangeStyleSpan,
    // as long as they aren't overridden by ones on copiedRangeStyleSpan.
665 666
    copiedRangeStyle->style()->merge(sourceDocumentStyle->style(), false);

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
667
    removeNodePreservingChildren(sourceDocumentStyleSpan);
668

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
669 670
    // Remove redundant styles.
    context = copiedRangeStyleSpan->parentNode();
671
    copiedRangeStyle->prepareToApplyAt(firstPositionInNode(context));
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
672
    copiedRangeStyle->removeBlockProperties();
673
    if (copiedRangeStyle->isEmpty()) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
674 675 676
        removeNodePreservingChildren(copiedRangeStyleSpan);
        return;
    }
677

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
678
    // Clear the redundant styles from the span's style attribute.
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
679 680
    // FIXME: If font-family:-webkit-monospace is non-redundant, then the font-size should stay, even if it
    // appears redundant.
681
    setNodeAttribute(static_cast<Element*>(copiedRangeStyleSpan), styleAttr, copiedRangeStyle->style()->cssText());
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
682 683
}

684 685 686 687 688 689
// Take the style attribute of a span and apply it to it's children instead.  This allows us to
// convert invalid HTML where a span contains block elements into valid HTML while preserving
// styles.
void ReplaceSelectionCommand::copyStyleToChildren(Node* parentNode, const CSSMutableStyleDeclaration* parentStyle)
{
    ASSERT(parentNode->hasTagName(spanTag));
690 691 692 693 694 695
    NodeVector childNodes;
    for (RefPtr<Node> childNode = parentNode->firstChild(); childNode; childNode = childNode->nextSibling())
        childNodes.append(childNode);
        
    for (NodeVector::const_iterator it = childNodes.begin(); it != childNodes.end(); it++) {
        Node* childNode = it->get();
696 697
        if (childNode->isTextNode() || !isBlock(childNode) || childNode->hasTagName(preTag)) {
            // In this case, put a span tag around the child node.
698 699
            RefPtr<Node> newNode = parentNode->cloneNode(false);
            ASSERT(newNode->hasTagName(spanTag));
700
            HTMLElement* newSpan = toHTMLElement(newNode.get());
701
            setNodeAttribute(newSpan, styleAttr, parentStyle->cssText());
702 703 704 705
            insertNodeAfter(newSpan, childNode);
            ExceptionCode ec = 0;
            newSpan->appendChild(childNode, ec);
            ASSERT(!ec);
706
            childNode = newSpan;
707 708 709 710
        } else if (childNode->isHTMLElement()) {
            // Copy the style attribute and merge them into the child node.  We don't want to override
            // existing styles, so don't clobber on merge.
            RefPtr<CSSMutableStyleDeclaration> newStyle = parentStyle->copy();
711
            HTMLElement* childElement = toHTMLElement(childNode);
712 713 714 715 716 717 718
            RefPtr<CSSMutableStyleDeclaration> existingStyles = childElement->getInlineStyleDecl()->copy();
            existingStyles->merge(newStyle.get(), false);
            setNodeAttribute(childElement, styleAttr, existingStyles->cssText());
        }
    }
}

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
void ReplaceSelectionCommand::mergeEndIfNeeded()
{
    if (!m_shouldMergeEnd)
        return;

    VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
    VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
    
    // Bail to avoid infinite recursion.
    if (m_movingParagraph) {
        ASSERT_NOT_REACHED();
        return;
    }
    
    // Merging two paragraphs will destroy the moved one's block styles.  Always move the end of inserted forward 
    // to preserve the block style of the paragraph already in the document, unless the paragraph to move would 
    // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
    // block styles.
    bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
    
    VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
    VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
741 742 743 744 745
   
    // Merging forward could result in deleting the destination anchor node.
    // To avoid this, we add a placeholder node before the start of the paragraph.
    if (endOfParagraph(startOfParagraphToMove) == destination) {
        RefPtr<Node> placeholder = createBreakElement(document());
746
        insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
747
        destination = VisiblePosition(positionBeforeNode(placeholder.get()));
748
    }
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
749 750

    moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
751
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
752 753
    // Merging forward will remove m_lastLeafInserted from the document.
    // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes.  The nodes are
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
754 755
    // only ever used to create positions where inserted content starts/ends.  Also, we sometimes insert content
    // directly into text nodes already in the document, in which case tracking inserted nodes is inadequate.
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
756
    if (mergeForward) {
757
        m_lastLeafInserted = destination.previous().deepEquivalent().deprecatedNode();
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
758
        if (!m_firstNodeInserted->inDocument())
759
            m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().deprecatedNode();
760 761 762 763
        // If we merged text nodes, m_lastLeafInserted could be null. If this is the case,
        // we use m_firstNodeInserted.
        if (!m_lastLeafInserted)
            m_lastLeafInserted = m_firstNodeInserted;
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
764 765 766
    }
}

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
static Node* enclosingInline(Node* node)
{
    while (ContainerNode* parent = node->parentNode()) {
        if (parent->isBlockFlow() || parent->hasTagName(bodyTag))
            return node;
        // Stop if any previous sibling is a block.
        for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
            if (sibling->isBlockFlow())
                return node;
        }
        node = parent;
    }
    return node;
}

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
static bool isInlineNodeWithStyle(const Node* node)
{
    // We don't want to skip over any block elements.
    if (!node->renderer() || !node->renderer()->isInline())
        return false;

    if (!node->isHTMLElement())
        return false;
    
    // We can skip over elements whose class attribute is
    // one of our internal classes.
    const HTMLElement* element = static_cast<const HTMLElement*>(node);
    AtomicString classAttributeValue = element->getAttribute(classAttr);
    if (classAttributeValue == AppleStyleSpanClass
        || classAttributeValue == AppleTabSpanClass
        || classAttributeValue == AppleConvertedSpace
        || classAttributeValue == ApplePasteAsQuotation)
        return true;

    // We can skip inline elements that don't have attributes or whose only
    // attribute is the style attribute.
    const NamedNodeMap* attributeMap = element->attributeMap();
    if (!attributeMap || attributeMap->isEmpty() || (attributeMap->length() == 1 && element->hasAttribute(styleAttr)))
        return true;

    return false;
}
    
mjs's avatar
mjs committed
810 811
void ReplaceSelectionCommand::doApply()
{
812
    VisibleSelection selection = endingSelection();
mjs's avatar
mjs committed
813
    ASSERT(selection.isCaretOrRange());
814 815
    ASSERT(selection.start().deprecatedNode());
    if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
justing's avatar
justing committed
816
        return;
justing's avatar
justing committed
817
    
mjs's avatar
mjs committed
818
    bool selectionIsPlainText = !selection.isContentRichlyEditable();
justing's avatar
justing committed
819
    
justing's avatar
justing committed
820
    Element* currentRoot = selection.rootEditableElement();
darin's avatar
darin committed
821
    ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
justing's avatar
justing committed
822
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
823 824 825
    if (performTrivialReplace(fragment))
        return;
    
826
    // We can skip matching the style if the selection is plain text.
827 828
    if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
        && (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
829 830
        m_matchStyle = false;
    
831 832 833 834
    if (m_matchStyle) {
        m_insertionStyle = EditingStyle::create(selection.start());
        m_insertionStyle->mergeTypingStyle(document());
    }
835

justing's avatar
justing committed
836 837
    VisiblePosition visibleStart = selection.visibleStart();
    VisiblePosition visibleEnd = selection.visibleEnd();
mjs's avatar
mjs committed
838
    
justing's avatar
justing committed
839 840 841
    bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
    bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
    
842
    Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
justing's avatar
justing committed
843
    
bdakin@apple.com's avatar
bdakin@apple.com committed
844
    Position insertionPos = selection.start();
845 846
    bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);

847
    if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
848
        startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
justing's avatar
justing committed
849
        m_preventNesting = false;
bdakin@apple.com's avatar
bdakin@apple.com committed
850
    
mjs's avatar
mjs committed
851
    if (selection.isRange()) {
justing's avatar
justing committed
852
        // When the end of the selection being pasted into is at the end of a paragraph, and that selection
justing's avatar
justing committed
853 854 855
        // spans multiple blocks, not merging may leave an empty line.
        // When the start of the selection being pasted into is at the start of a block, not merging 
        // will leave hanging block(s).
bdakin@apple.com's avatar
bdakin@apple.com committed
856 857 858
        // Merge blocks if the start of the selection was in a Mail blockquote, since we handle  
        // that case specially to prevent nesting. 
        bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
justing's avatar
justing committed
859 860
        // FIXME: We should only expand to include fully selected special elements if we are copying a 
        // selection and pasting it on top of itself.
justing's avatar
justing committed
861
        deleteSelection(false, mergeBlocksAfterDelete, true, false);
justing's avatar
justing committed
862
        visibleStart = endingSelection().visibleStart();
justing's avatar
justing committed
863
        if (fragment.hasInterchangeNewlineAtStart()) {
mjs's avatar
mjs committed
864 865 866
            if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
                if (!isEndOfDocument(visibleStart))
                    setEndingSelection(visibleStart.next());
justing's avatar
justing committed
867
            } else
mjs's avatar
mjs committed
868 869
                insertParagraphSeparator();
        }
justing's avatar
justing committed
870
        insertionPos = endingSelection().start();
justing's avatar
justing committed
871
    } else {
mjs's avatar
mjs committed
872
        ASSERT(selection.isCaret());
justing's avatar
justing committed
873
        if (fragment.hasInterchangeNewlineAtStart()) {
874
            VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
justing's avatar
justing committed
875 876 877
            if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
                setEndingSelection(next);
            else 
mjs's avatar
mjs committed
878 879
                insertParagraphSeparator();
        }
justing's avatar
justing committed
880 881 882
        // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
        // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.  
        // As long as the  div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>, 
bdakin@apple.com's avatar
bdakin@apple.com committed
883
        // not <div>xbar<div>bar</div><div>bazx</div></div>.
bdakin@apple.com's avatar
bdakin@apple.com committed
884
        // Don't do this if the selection started in a Mail blockquote.