2 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "ReplaceSelectionCommand.h"
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"
37 #include "DocumentFragment.h"
38 #include "EditingText.h"
40 #include "EventNames.h"
42 #include "FrameSelection.h"
43 #include "HTMLElement.h"
44 #include "HTMLInputElement.h"
45 #include "HTMLInterchange.h"
46 #include "HTMLNames.h"
48 #include "RenderObject.h"
49 #include "SmartReplace.h"
50 #include "TextIterator.h"
51 #include "htmlediting.h"
53 #include "visible_units.h"
54 #include <wtf/StdLibExtras.h>
55 #include <wtf/Vector.h>
59 typedef Vector<RefPtr<Node> > NodeVector;
61 using namespace HTMLNames;
63 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
65 // --- ReplacementFragment helper class
67 class ReplacementFragment {
68 WTF_MAKE_NONCOPYABLE(ReplacementFragment);
70 ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&);
72 Node* firstChild() const;
73 Node* lastChild() const;
77 bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
78 bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
80 void removeNode(PassRefPtr<Node>);
81 void removeNodePreservingChildren(Node*);
84 PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* context);
85 void removeUnrenderedNodes(Node*);
86 void restoreTestRenderingNodesToFragment(StyledElement*);
87 void removeInterchangeNodes(Node*);
89 void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
91 RefPtr<Document> m_document;
92 RefPtr<DocumentFragment> m_fragment;
94 bool m_hasInterchangeNewlineAtStart;
95 bool m_hasInterchangeNewlineAtEnd;
98 static bool isInterchangeNewlineNode(const Node *node)
100 DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
101 return node && node->hasTagName(brTag) &&
102 static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
105 static bool isInterchangeConvertedSpaceSpan(const Node *node)
107 DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
108 return node->isHTMLElement() &&
109 static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
112 static Position positionAvoidingPrecedingNodes(Position pos)
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()))
118 // We also stop when changing block flow elements because even though the visual position is the
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()))
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)
139 if (!m_fragment->firstChild())
142 RefPtr<Element> editableRoot = selection.rootEditableElement();
143 ASSERT(editableRoot);
147 Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
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());
157 RefPtr<Node> styleNode = selection.base().deprecatedNode();
158 RefPtr<StyledElement> holder = insertFragmentForTestRendering(styleNode.get());
160 removeInterchangeNodes(m_fragment.get());
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);
171 if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
172 restoreTestRenderingNodesToFragment(holder.get());
175 m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
176 if (!m_fragment->firstChild())
178 holder = insertFragmentForTestRendering(styleNode.get());
181 removeInterchangeNodes(holder.get());
183 removeUnrenderedNodes(holder.get());
184 restoreTestRenderingNodesToFragment(holder.get());
188 bool ReplacementFragment::isEmpty() const
190 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
193 Node *ReplacementFragment::firstChild() const
195 return m_fragment ? m_fragment->firstChild() : 0;
198 Node *ReplacementFragment::lastChild() const
200 return m_fragment ? m_fragment->lastChild() : 0;
203 void ReplacementFragment::removeNodePreservingChildren(Node *node)
208 while (RefPtr<Node> n = node->firstChild()) {
210 insertNodeBefore(n.release(), node);
215 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
220 ContainerNode* parent = node->nonShadowBoundaryParentNode();
224 ExceptionCode ec = 0;
225 parent->removeChild(node.get(), ec);
229 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
231 if (!node || !refNode)
234 ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
238 ExceptionCode ec = 0;
239 parent->insertBefore(node, refNode, ec);
243 PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* context)
245 HTMLElement* body = m_document->body();
249 RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
251 ExceptionCode ec = 0;
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.
257 while (n && (!n->isElementNode() || n->hasTagName(brTag)))
260 RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n);
261 CSSStyleDeclaration* style = holder->style();
262 style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec);
264 style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec);
268 holder->appendChild(m_fragment, ec);
271 body->appendChild(holder.get(), ec);
274 m_document->updateLayoutIgnorePendingStylesheets();
276 return holder.release();
279 void ReplacementFragment::restoreTestRenderingNodesToFragment(StyledElement* holder)
284 ExceptionCode ec = 0;
285 while (RefPtr<Node> node = holder->firstChild()) {
286 holder->removeChild(node.get(), ec);
288 m_fragment->appendChild(node.get(), ec);
293 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
295 Vector<RefPtr<Node> > unrendered;
297 for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
298 if (!isNodeRendered(node) && !isTableStructureNode(node))
299 unrendered.append(node);
301 size_t n = unrendered.size();
302 for (size_t i = 0; i < n; ++i)
303 removeNode(unrendered[i]);
306 void ReplacementFragment::removeInterchangeNodes(Node* container)
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();
312 if (isInterchangeNewlineNode(node)) {
313 m_hasInterchangeNewlineAtStart = true;
317 node = node->firstChild();
319 if (!container->hasChildNodes())
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();
325 if (isInterchangeNewlineNode(node)) {
326 m_hasInterchangeNewlineAtEnd = true;
330 node = node->lastChild();
333 node = container->firstChild();
335 Node *next = node->traverseNextNode();
336 if (isInterchangeConvertedSpaceSpan(node)) {
338 while ((n = node->firstChild())) {
340 insertNodeBefore(n, node);
344 next = n->traverseNextNode();
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)
363 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
365 Position existing = endOfExistingContent.deepEquivalent();
366 Position inserted = endOfInsertedContent.deepEquivalent();
367 bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
368 return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
371 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
373 if (m_movingParagraph)
376 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
377 VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
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()))
389 return !selectionStartWasStartOfParagraph
390 && !fragmentHasInterchangeNewlineAtStart
391 && isStartOfParagraph(startOfInsertedContent)
392 && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
393 && shouldMerge(startOfInsertedContent, prev);
396 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
398 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
399 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
403 return !selectionEndWasEndOfParagraph
404 && isEndOfParagraph(endOfInsertedContent)
405 && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
406 && shouldMerge(endOfInsertedContent, next);
409 static bool isMailPasteAsQuotationNode(const Node* node)
411 return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
414 // Wrap CompositeEditCommand::removeNodePreservingChildren() so we can update the nodes we track
415 void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node)
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);
424 // Wrap CompositeEditCommand::removeNodeAndPruneAncestors() so we can update the nodes we track
425 void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node)
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;
432 CompositeEditCommand::removeNodeAndPruneAncestors(node);
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;
441 static bool isHeaderElement(Node* a)
446 return a->hasTagName(h1Tag) ||
447 a->hasTagName(h2Tag) ||
448 a->hasTagName(h3Tag) ||
449 a->hasTagName(h4Tag) ||
450 a->hasTagName(h5Tag);
453 static bool haveSameTagName(Node* a, Node* b)
455 return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName();
458 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
460 if (source.isNull() || destination.isNull())
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);
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()
481 RefPtr<Node> pastEndNode = m_lastLeafInserted ? m_lastLeafInserted->traverseNextNode() : 0;
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
486 next = node->traverseNextNode();
487 if (!node->isStyledElement())
490 StyledElement* element = static_cast<StyledElement*>(node.get());
492 CSSMutableStyleDeclaration* inlineStyle = element->inlineStyleDecl();
493 RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
495 ContainerNode* context = element->parentNode();
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);
501 newInlineStyle->removeStyleFromRulesAndContext(element, document()->documentElement());
503 newInlineStyle->removeStyleFromRulesAndContext(element, context);
506 if (!inlineStyle || newInlineStyle->isEmpty()) {
507 if (isStyleSpanOrSpanWithOnlyStyleAttribute(element))
508 removeNodePreservingChildren(element);
510 removeNodeAttribute(element, styleAttr);
511 } else if (newInlineStyle->style()->length() != inlineStyle->length())
512 setNodeAttribute(element, styleAttr, newInlineStyle->style()->cssText());
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);
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);
535 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds()
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;
548 RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode();
549 removeNode(m_lastLeafInserted.get());
550 m_lastLeafInserted = previous;
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;
563 RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling();
564 removeNode(m_firstNodeInserted.get());
565 m_firstNodeInserted = next;
569 void ReplaceSelectionCommand::handlePasteAsQuotationNode()
571 Node* node = m_firstNodeInserted.get();
572 if (isMailPasteAsQuotationNode(node))
573 removeNodeAttribute(static_cast<Element*>(node), classAttr);
576 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent()
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);
582 lastNode = enclosingSelect;
583 return lastPositionInOrAfterNode(lastNode);
586 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent()
588 // Return the inserted content's first VisiblePosition.
589 return VisiblePosition(nextCandidate(positionInParentBeforeNode(m_firstNodeInserted.get())));
592 static void removeHeadContents(ReplacementFragment& fragment)
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);
604 next = node->traverseNextNode();
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)
612 Node* topNode = fragment.firstChild();
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))
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))
624 Node* wrappingStyleSpan = topNode;
625 RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
626 String styleText = styleAtInsertionPos->style()->cssText();
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))
633 fragment.removeNodePreservingChildren(wrappingStyleSpan);
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
645 void ReplaceSelectionCommand::handleStyleSpans()
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);
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)
663 RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->getInlineStyleDecl());
664 ContainerNode* context = wrappingStyleSpan->parentNode();
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);
670 context = document()->documentElement();
672 // This operation requires that only editing styles to be removed from sourceDocumentStyle.
673 style->prepareToApplyAt(firstPositionInNode(context));
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();
682 if (style->isEmpty() || !wrappingStyleSpan->firstChild())
683 removeNodePreservingChildren(wrappingStyleSpan);
685 setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->cssText());
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
691 void ReplaceSelectionCommand::copyStyleToChildren(Node* parentNode, const CSSMutableStyleDeclaration* parentStyle)
693 ASSERT(parentNode->hasTagName(spanTag));
694 NodeVector childNodes;
695 for (RefPtr<Node> childNode = parentNode->firstChild(); childNode; childNode = childNode->nextSibling())
696 childNodes.append(childNode);
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);
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());
723 void ReplaceSelectionCommand::mergeEndIfNeeded()
725 if (!m_shouldMergeEnd)
728 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
729 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
731 // Bail to avoid infinite recursion.
732 if (m_movingParagraph) {
733 ASSERT_NOT_REACHED();
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
741 bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
743 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
744 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
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()));
754 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
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.
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;
771 static Node* enclosingInline(Node* node)
773 while (ContainerNode* parent = node->parentNode()) {
774 if (parent->isBlockFlow() || parent->hasTagName(bodyTag))
776 // Stop if any previous sibling is a block.
777 for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
778 if (sibling->isBlockFlow())
786 static bool isInlineNodeWithStyle(const Node* node)
788 // We don't want to skip over any block elements.
792 if (!node->isHTMLElement())
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)
804 return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
807 void ReplaceSelectionCommand::doApply()
809 VisibleSelection selection = endingSelection();
810 ASSERT(selection.isCaretOrRange());
811 ASSERT(selection.start().deprecatedNode());
812 if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
815 bool selectionIsPlainText = !selection.isContentRichlyEditable();
817 Element* currentRoot = selection.rootEditableElement();
818 ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
820 if (performTrivialReplace(fragment))
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;
829 m_insertionStyle = EditingStyle::create(selection.start());
830 m_insertionStyle->mergeTypingStyle(document());
833 VisiblePosition visibleStart = selection.visibleStart();
834 VisiblePosition visibleEnd = selection.visibleEnd();
836 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
837 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
839 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
841 Position insertionPos = selection.start();
842 bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
844 if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
845 startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
846 m_preventNesting = false;
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());
865 insertParagraphSeparator();
867 insertionPos = endingSelection().start();
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);
875 insertParagraphSeparator();
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());
886 insertionPos = endingSelection().start();
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);
902 // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
903 prepareWhitespaceAtPositionForSplit(insertionPos);
905 // If the downstream node has been removed there's no point in continuing.
906 if (!insertionPos.downstream().deprecatedNode())
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;
915 originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
917 startBlock = enclosingBlock(insertionPos.deprecatedNode());
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);
930 // Paste at start or end of link goes outside of link.
931 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
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();
938 removeHeadContents(fragment);
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);
945 // Paste into run of tabs splits the tab span.
946 insertionPos = positionOutsideTabSpan(insertionPos);
948 bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
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());
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());
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.
974 // We're finished if there is nothing to add.
975 if (fragment.isEmpty() || !fragment.firstChild())
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.
988 VisiblePosition startOfInsertedContent, endOfInsertedContent;
990 RefPtr<Node> refNode = fragment.firstChild();
991 RefPtr<Node> node = refNode->nextSibling();
993 fragment.removeNode(refNode);
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);
1000 insertNodeAtAndUpdateNodesInserted(refNode, insertionPos);
1002 // Mutation events (bug 22634) may have already removed the inserted content
1003 if (!refNode->inDocument())
1006 bool plainTextFragment = isPlainTextMarkup(refNode.get());
1009 RefPtr<Node> next = node->nextSibling();
1010 fragment.removeNode(node.get());
1011 insertNodeAfterAndUpdateNodesInserted(node, refNode.get());
1013 // Mutation events (bug 22634) may have already removed the inserted content
1014 if (!node->inDocument())
1018 if (node && plainTextFragment)
1019 plainTextFragment = isPlainTextMarkup(node.get());
1023 removeUnrenderedTextNodesAtEnds();
1025 removeRedundantStylesAndKeepStyleSpanInline();
1027 if (!handledStyleSpans)
1030 // Mutation events (bug 20161) may have already removed the inserted content
1031 if (!m_firstNodeInserted || !m_firstNodeInserted->inDocument())
1034 endOfInsertedContent = positionAtEndOfInsertedContent();
1035 startOfInsertedContent = positionAtStartOfInsertedContent();
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());
1042 Position lastPositionToSelect;
1044 bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd();
1046 if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR)))
1047 removeNodeAndPruneAncestors(endBR);
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);
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());
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())
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();
1086 endOfInsertedContent = positionAtEndOfInsertedContent();
1087 startOfInsertedContent = positionAtStartOfInsertedContent();
1089 if (interchangeNewlineAtEnd) {
1090 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
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())));
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);
1105 // Select up to the paragraph separator that was added.
1106 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
1107 updateNodesInserted(lastPositionToSelect.deprecatedNode());
1110 // Select up to the beginning of the next paragraph.
1111 lastPositionToSelect = next.deepEquivalent().downstream();
1117 handlePasteAsQuotationNode();
1119 endOfInsertedContent = positionAtEndOfInsertedContent();
1120 startOfInsertedContent = positionAtStartOfInsertedContent();
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.
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() : " ");
1139 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1140 insertNodeAfterAndUpdateNodesInserted(node, endNode);
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() : " ");
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;
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;
1169 completeHTMLReplacement(lastPositionToSelect);
1172 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
1174 if (!endBR || !endBR->inDocument())
1177 VisiblePosition visiblePos(positionBeforeNode(endBR));
1179 // Don't remove the br if nothing was inserted.
1180 if (visiblePos.previous() == originalVisPosBeforeEndBR)
1183 // Remove the br if it is collapsed away and so is unnecessary.
1184 if (!document()->inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
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);
1192 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
1197 // FIXME: This should never not be the case.
1198 if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastLeafInserted && m_lastLeafInserted->inDocument()) {
1200 start = positionAtStartOfInsertedContent().deepEquivalent();
1201 end = positionAtEndOfInsertedContent().deepEquivalent();
1203 // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
1204 rebalanceWhitespaceAt(start);
1205 rebalanceWhitespaceAt(end);
1208 ASSERT(m_insertionStyle);
1209 applyStyle(m_insertionStyle.get(), start, end);
1212 if (lastPositionToSelect.isNotNull())
1213 end = lastPositionToSelect;
1214 } else if (lastPositionToSelect.isNotNull())
1215 start = end = lastPositionToSelect;
1219 if (m_selectReplacement)
1220 setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1222 setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1225 EditAction ReplaceSelectionCommand::editingAction() const
1227 return m_editAction;
1230 void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1232 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1233 insertNodeAfter(insertChild, refChild);
1234 updateNodesInserted(nodeToUpdate);
1237 void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild, const Position& p)
1239 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1240 insertNodeAt(insertChild, p);
1241 updateNodesInserted(nodeToUpdate);
1244 void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1246 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1247 insertNodeBefore(insertChild, refChild);
1248 updateNodesInserted(nodeToUpdate);
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)
1255 RefPtr<Node> listElement = prpListElement;
1257 while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1)
1258 listElement = listElement->firstChild();
1260 bool isStart = isStartOfParagraph(insertPos);
1261 bool isEnd = isEndOfParagraph(insertPos);
1262 bool isMiddle = !isStart && !isEnd;
1263 Node* lastNode = insertionBlock;
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.
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);
1274 while (RefPtr<Node> listItem = listElement->firstChild()) {
1275 ExceptionCode ec = 0;
1276 toContainerNode(listElement.get())->removeChild(listItem.get(), ec);
1278 if (isStart || isMiddle)
1279 insertNodeBefore(listItem, lastNode);
1281 insertNodeAfter(listItem, lastNode);
1282 lastNode = listItem.get();
1284 ASSERT_NOT_REACHED();
1286 if (isStart || isMiddle)
1287 lastNode = lastNode->previousSibling();
1289 insertNodeAfter(createListItemElement(document()), lastNode);
1290 updateNodesInserted(lastNode);
1294 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
1299 if (!m_firstNodeInserted)
1300 m_firstNodeInserted = node;
1302 if (node == m_lastLeafInserted)
1305 m_lastLeafInserted = node->lastDescendant();
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)
1314 if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
1317 // FIXME: Would be nice to handle smart replace in the fast path.
1318 if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
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.
1324 Position start = endingSelection().start();
1325 Position end = replaceSelectedTextInNode(textNode->data());
1329 VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
1331 setEndingSelection(selectionAfterReplace);
1336 } // namespace WebCore