2 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2009, 2010, 2011 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "ReplaceSelectionCommand.h"
30 #include "ApplyStyleCommand.h"
31 #include "BeforeTextInsertedEvent.h"
32 #include "BreakBlockquoteCommand.h"
33 #include "CSSComputedStyleDeclaration.h"
34 #include "CSSMutableStyleDeclaration.h"
35 #include "CSSPropertyNames.h"
36 #include "CSSValueKeywords.h"
38 #include "DocumentFragment.h"
39 #include "EditingText.h"
41 #include "EventNames.h"
43 #include "FrameSelection.h"
44 #include "HTMLElement.h"
45 #include "HTMLInputElement.h"
46 #include "HTMLInterchange.h"
47 #include "HTMLNames.h"
49 #include "RenderObject.h"
50 #include "RenderText.h"
51 #include "SmartReplace.h"
52 #include "TextIterator.h"
53 #include "htmlediting.h"
55 #include "visible_units.h"
56 #include <wtf/StdLibExtras.h>
57 #include <wtf/Vector.h>
61 typedef Vector<RefPtr<Node> > NodeVector;
63 using namespace HTMLNames;
65 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
67 // --- ReplacementFragment helper class
69 class ReplacementFragment {
70 WTF_MAKE_NONCOPYABLE(ReplacementFragment);
72 ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&);
74 Node* firstChild() const;
75 Node* lastChild() const;
79 bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
80 bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
82 void removeNode(PassRefPtr<Node>);
83 void removeNodePreservingChildren(Node*);
86 PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* rootEditableNode);
87 void removeUnrenderedNodes(Node*);
88 void restoreAndRemoveTestRenderingNodesToFragment(StyledElement*);
89 void removeInterchangeNodes(Node*);
91 void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
93 RefPtr<Document> m_document;
94 RefPtr<DocumentFragment> m_fragment;
96 bool m_hasInterchangeNewlineAtStart;
97 bool m_hasInterchangeNewlineAtEnd;
100 static bool isInterchangeNewlineNode(const Node *node)
102 DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
103 return node && node->hasTagName(brTag) &&
104 static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
107 static bool isInterchangeConvertedSpaceSpan(const Node *node)
109 DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
110 return node->isHTMLElement() &&
111 static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
114 static Position positionAvoidingPrecedingNodes(Position pos)
116 // If we're already on a break, it's probably a placeholder and we shouldn't change our position.
117 if (editingIgnoresContent(pos.deprecatedNode()))
120 // We also stop when changing block flow elements because even though the visual position is the
123 // The two positions above are the same visual position, but we want to stay in the same block.
124 Node* stopNode = pos.deprecatedNode()->enclosingBlockFlowElement();
125 while (stopNode != pos.deprecatedNode() && VisiblePosition(pos) == VisiblePosition(pos.next()))
130 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const VisibleSelection& selection)
131 : m_document(document),
132 m_fragment(fragment),
133 m_matchStyle(matchStyle),
134 m_hasInterchangeNewlineAtStart(false),
135 m_hasInterchangeNewlineAtEnd(false)
141 if (!m_fragment->firstChild())
144 RefPtr<Element> editableRoot = selection.rootEditableElement();
145 ASSERT(editableRoot);
149 Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
151 if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
152 // FIXME: Remove these checks once textareas and textfields actually register an event handler.
153 !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
154 editableRoot->rendererIsRichlyEditable()) {
155 removeInterchangeNodes(m_fragment.get());
159 RefPtr<StyledElement> holder = insertFragmentForTestRendering(editableRoot.get());
161 removeInterchangeNodes(m_fragment.get());
165 RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
166 String text = plainText(range.get(), TextIteratorEmitsOriginalText);
168 removeInterchangeNodes(holder.get());
169 removeUnrenderedNodes(holder.get());
170 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
172 // Give the root a chance to change the text.
173 RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
174 ExceptionCode ec = 0;
175 editableRoot->dispatchEvent(evt, ec);
177 if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
178 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
180 m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
181 if (!m_fragment->firstChild())
184 holder = insertFragmentForTestRendering(editableRoot.get());
185 removeInterchangeNodes(holder.get());
186 removeUnrenderedNodes(holder.get());
187 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
191 bool ReplacementFragment::isEmpty() const
193 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
196 Node *ReplacementFragment::firstChild() const
198 return m_fragment ? m_fragment->firstChild() : 0;
201 Node *ReplacementFragment::lastChild() const
203 return m_fragment ? m_fragment->lastChild() : 0;
206 void ReplacementFragment::removeNodePreservingChildren(Node *node)
211 while (RefPtr<Node> n = node->firstChild()) {
213 insertNodeBefore(n.release(), node);
218 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
223 ContainerNode* parent = node->nonShadowBoundaryParentNode();
227 ExceptionCode ec = 0;
228 parent->removeChild(node.get(), ec);
232 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
234 if (!node || !refNode)
237 ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
241 ExceptionCode ec = 0;
242 parent->insertBefore(node, refNode, ec);
246 PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
248 RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
250 ExceptionCode ec = 0;
252 holder->appendChild(m_fragment, ec);
255 rootEditableElement->appendChild(holder.get(), ec);
258 m_document->updateLayoutIgnorePendingStylesheets();
260 return holder.release();
263 void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(StyledElement* holder)
268 ExceptionCode ec = 0;
269 while (RefPtr<Node> node = holder->firstChild()) {
270 holder->removeChild(node.get(), ec);
272 m_fragment->appendChild(node.get(), ec);
279 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
281 Vector<RefPtr<Node> > unrendered;
283 for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
284 if (!isNodeRendered(node) && !isTableStructureNode(node))
285 unrendered.append(node);
287 size_t n = unrendered.size();
288 for (size_t i = 0; i < n; ++i)
289 removeNode(unrendered[i]);
292 void ReplacementFragment::removeInterchangeNodes(Node* container)
294 // Interchange newlines at the "start" of the incoming fragment must be
295 // either the first node in the fragment or the first leaf in the fragment.
296 Node* node = container->firstChild();
298 if (isInterchangeNewlineNode(node)) {
299 m_hasInterchangeNewlineAtStart = true;
303 node = node->firstChild();
305 if (!container->hasChildNodes())
307 // Interchange newlines at the "end" of the incoming fragment must be
308 // either the last node in the fragment or the last leaf in the fragment.
309 node = container->lastChild();
311 if (isInterchangeNewlineNode(node)) {
312 m_hasInterchangeNewlineAtEnd = true;
316 node = node->lastChild();
319 node = container->firstChild();
321 Node *next = node->traverseNextNode();
322 if (isInterchangeConvertedSpaceSpan(node)) {
324 while ((n = node->firstChild())) {
326 insertNodeBefore(n, node);
330 next = n->traverseNextNode();
336 inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node* node)
341 if (!m_firstNodeInserted)
342 m_firstNodeInserted = node;
344 m_lastNodeInserted = node;
347 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node* node)
349 if (m_firstNodeInserted == node)
350 m_firstNodeInserted = node->traverseNextNode();
351 if (m_lastNodeInserted == node)
352 m_lastNodeInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling();
355 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node* node)
357 if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
358 m_firstNodeInserted = 0;
359 m_lastNodeInserted = 0;
360 } else if (m_firstNodeInserted == node)
361 m_firstNodeInserted = m_firstNodeInserted->traverseNextSibling();
362 else if (m_lastNodeInserted == node)
363 m_lastNodeInserted = m_lastNodeInserted->traversePreviousSibling();
366 ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
367 : CompositeEditCommand(document)
368 , m_selectReplacement(options & SelectReplacement)
369 , m_smartReplace(options & SmartReplace)
370 , m_matchStyle(options & MatchStyle)
371 , m_documentFragment(fragment)
372 , m_preventNesting(options & PreventNesting)
373 , m_movingParagraph(options & MovingParagraph)
374 , m_editAction(editAction)
375 , m_shouldMergeEnd(false)
379 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
381 Position existing = endOfExistingContent.deepEquivalent();
382 Position inserted = endOfInsertedContent.deepEquivalent();
383 bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
384 return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
387 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
389 if (m_movingParagraph)
392 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
393 VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
397 // When we have matching quote levels, its ok to merge more frequently.
398 // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
399 // And we should only merge here if the selection start was inside a mail blockquote. This prevents against removing a
400 // blockquote from newly pasted quoted content that was pasted into an unquoted position. If that unquoted position happens
401 // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
402 if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
405 return !selectionStartWasStartOfParagraph
406 && !fragmentHasInterchangeNewlineAtStart
407 && isStartOfParagraph(startOfInsertedContent)
408 && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
409 && shouldMerge(startOfInsertedContent, prev);
412 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
414 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
415 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
419 return !selectionEndWasEndOfParagraph
420 && isEndOfParagraph(endOfInsertedContent)
421 && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
422 && shouldMerge(endOfInsertedContent, next);
425 static bool isMailPasteAsQuotationNode(const Node* node)
427 return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
430 static bool isHeaderElement(Node* a)
435 return a->hasTagName(h1Tag) ||
436 a->hasTagName(h2Tag) ||
437 a->hasTagName(h3Tag) ||
438 a->hasTagName(h4Tag) ||
439 a->hasTagName(h5Tag);
442 static bool haveSameTagName(Node* a, Node* b)
444 return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName();
447 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
449 if (source.isNull() || destination.isNull())
452 Node* sourceNode = source.deepEquivalent().deprecatedNode();
453 Node* destinationNode = destination.deepEquivalent().deprecatedNode();
454 Node* sourceBlock = enclosingBlock(sourceNode);
455 Node* destinationBlock = enclosingBlock(destinationNode);
456 return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
457 sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) &&
458 enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
459 enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
460 (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
461 // Don't merge to or from a position before or after a block because it would
462 // be a no-op and cause infinite recursion.
463 !isBlock(sourceNode) && !isBlock(destinationNode);
466 // Style rules that match just inserted elements could change their appearance, like
467 // a div inserted into a document with div { display:inline; }.
468 void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
470 RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
472 for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
473 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
475 next = node->traverseNextNode();
476 if (!node->isStyledElement())
479 StyledElement* element = static_cast<StyledElement*>(node.get());
481 CSSMutableStyleDeclaration* inlineStyle = element->inlineStyleDecl();
482 RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
484 ContainerNode* context = element->parentNode();
486 // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
487 // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
488 Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
490 newInlineStyle->removeStyleFromRulesAndContext(element, document()->documentElement());
492 newInlineStyle->removeStyleFromRulesAndContext(element, context);
495 if (!inlineStyle || newInlineStyle->isEmpty()) {
496 if (isStyleSpanOrSpanWithOnlyStyleAttribute(element)) {
497 insertedNodes.willRemoveNodePreservingChildren(element);
498 removeNodePreservingChildren(element);
501 removeNodeAttribute(element, styleAttr);
502 } else if (newInlineStyle->style()->length() != inlineStyle->length())
503 setNodeAttribute(element, styleAttr, newInlineStyle->style()->cssText());
505 // FIXME: Tolerate differences in id, class, and style attributes.
506 if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
507 && VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
508 && VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
509 insertedNodes.willRemoveNodePreservingChildren(element);
510 removeNodePreservingChildren(element);
514 if (element->parentNode()->rendererIsRichlyEditable())
515 removeNodeAttribute(element, contenteditableAttr);
517 // WebKit used to not add display: inline and float: none on copy.
518 // Keep this code around for backward compatibility
519 if (isLegacyAppleStyleSpan(element)) {
520 if (!element->firstChild()) {
521 insertedNodes.willRemoveNodePreservingChildren(element);
522 removeNodePreservingChildren(element);
525 // There are other styles that style rules can give to style spans,
526 // but these are the two important ones because they'll prevent
527 // inserted content from appearing in the right paragraph.
528 // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
529 // results. We already know one issue because td elements ignore their display property
530 // in quirks mode (which Mail.app is always in). We should look for an alternative.
531 if (isBlock(element))
532 element->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline);
533 if (element->renderer() && element->renderer()->style()->isFloating())
534 element->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone);
539 static inline bool nodeHasVisibleRenderText(Text* text)
541 return text->renderer() && toRenderText(text->renderer())->renderedTextLength() > 0;
544 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
546 document()->updateLayoutIgnorePendingStylesheets();
548 Node* lastLeafInserted = insertedNodes.lastLeafInserted();
549 if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(static_cast<Text*>(lastLeafInserted))
550 && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
551 && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
552 insertedNodes.willRemoveNode(lastLeafInserted);
553 removeNode(lastLeafInserted);
556 // We don't have to make sure that firstNodeInserted isn't inside a select or script element, because
557 // it is a top level node in the fragment and the user can't insert into those elements.
558 Node* firstNodeInserted = insertedNodes.firstNodeInserted();
559 lastLeafInserted = insertedNodes.lastLeafInserted();
560 if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(static_cast<Text*>(firstNodeInserted))) {
561 insertedNodes.willRemoveNode(firstNodeInserted);
562 removeNode(firstNodeInserted);
566 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
568 // FIXME: Why is this hack here? What's special about <select> tags?
569 Node* enclosingSelect = enclosingNodeWithTag(m_endOfInsertedContent, selectTag);
570 return enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent;
573 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
575 return m_startOfInsertedContent;
578 static void removeHeadContents(ReplacementFragment& fragment)
581 for (Node* node = fragment.firstChild(); node; node = next) {
582 if (node->hasTagName(baseTag)
583 || node->hasTagName(linkTag)
584 || node->hasTagName(metaTag)
585 || node->hasTagName(styleTag)
586 || node->hasTagName(titleTag)) {
587 next = node->traverseNextSibling();
588 fragment.removeNode(node);
590 next = node->traverseNextNode();
594 // Remove style spans before insertion if they are unnecessary. It's faster because we'll
595 // avoid doing a layout.
596 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
598 Node* topNode = fragment.firstChild();
600 // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
601 // and doesn't receive the optimization.
602 if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
605 // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
606 // before inserting it. Look for and handle style spans after insertion.
607 if (!isLegacyAppleStyleSpan(topNode))
610 Node* wrappingStyleSpan = topNode;
611 RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
612 String styleText = styleAtInsertionPos->style()->cssText();
614 // FIXME: This string comparison is a naive way of comparing two styles.
615 // We should be taking the diff and check that the diff is empty.
616 if (styleText != static_cast<Element*>(wrappingStyleSpan)->getAttribute(styleAttr))
619 fragment.removeNodePreservingChildren(wrappingStyleSpan);
623 // At copy time, WebKit wraps copied content in a span that contains the source document's
624 // default styles. If the copied Range inherits any other styles from its ancestors, we put
625 // those styles on a second span.
626 // This function removes redundant styles from those spans, and removes the spans if all their
627 // styles are redundant.
628 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
629 // We should remove styles from spans that are overridden by all of their children, either here
631 void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
633 HTMLElement* wrappingStyleSpan = 0;
634 // The style span that contains the source document's default style should be at
635 // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
636 // so search for the top level style span instead of assuming it's at the top.
637 for (Node* node = insertedNodes.firstNodeInserted(); node; node = node->traverseNextNode()) {
638 if (isLegacyAppleStyleSpan(node)) {
639 wrappingStyleSpan = toHTMLElement(node);
644 // There might not be any style spans if we're pasting from another application or if
645 // we are here because of a document.execCommand("InsertHTML", ...) call.
646 if (!wrappingStyleSpan)
649 RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->getInlineStyleDecl());
650 ContainerNode* context = wrappingStyleSpan->parentNode();
652 // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
653 // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
654 Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
656 context = document()->documentElement();
658 // This operation requires that only editing styles to be removed from sourceDocumentStyle.
659 style->prepareToApplyAt(firstPositionInNode(context));
661 // Remove block properties in the span's style. This prevents properties that probably have no effect
662 // currently from affecting blocks later if the style is cloned for a new block element during a future
663 // editing operation.
664 // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
665 // with block styles by the editing engine used to style them. WebKit doesn't do this, but others might.
666 style->removeBlockProperties();
668 if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
669 insertedNodes.willRemoveNodePreservingChildren(wrappingStyleSpan);
670 removeNodePreservingChildren(wrappingStyleSpan);
672 setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->cssText());
675 void ReplaceSelectionCommand::mergeEndIfNeeded()
677 if (!m_shouldMergeEnd)
680 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
681 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
683 // Bail to avoid infinite recursion.
684 if (m_movingParagraph) {
685 ASSERT_NOT_REACHED();
689 // Merging two paragraphs will destroy the moved one's block styles. Always move the end of inserted forward
690 // to preserve the block style of the paragraph already in the document, unless the paragraph to move would
691 // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
693 bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
695 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
696 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
698 // Merging forward could result in deleting the destination anchor node.
699 // To avoid this, we add a placeholder node before the start of the paragraph.
700 if (endOfParagraph(startOfParagraphToMove) == destination) {
701 RefPtr<Node> placeholder = createBreakElement(document());
702 insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
703 destination = VisiblePosition(positionBeforeNode(placeholder.get()));
706 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
708 // Merging forward will remove m_endOfInsertedContent from the document.
710 if (m_startOfInsertedContent.isOrphan())
711 m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
712 m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
713 // If we merged text nodes, m_endOfInsertedContent could be null. If this is the case, we use m_startOfInsertedContent.
714 if (m_endOfInsertedContent.isNull())
715 m_endOfInsertedContent = m_startOfInsertedContent;
719 static Node* enclosingInline(Node* node)
721 while (ContainerNode* parent = node->parentNode()) {
722 if (parent->isBlockFlow() || parent->hasTagName(bodyTag))
724 // Stop if any previous sibling is a block.
725 for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
726 if (sibling->isBlockFlow())
734 static bool isInlineNodeWithStyle(const Node* node)
736 // We don't want to skip over any block elements.
740 if (!node->isHTMLElement())
743 // We can skip over elements whose class attribute is
744 // one of our internal classes.
745 const HTMLElement* element = static_cast<const HTMLElement*>(node);
746 const AtomicString& classAttributeValue = element->getAttribute(classAttr);
747 if (classAttributeValue == AppleTabSpanClass
748 || classAttributeValue == AppleConvertedSpace
749 || classAttributeValue == ApplePasteAsQuotation)
752 return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
755 inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
757 Node* containgBlock = enclosingBlock(insertionPos.containerNode());
758 return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
761 void ReplaceSelectionCommand::doApply()
763 VisibleSelection selection = endingSelection();
764 ASSERT(selection.isCaretOrRange());
765 ASSERT(selection.start().deprecatedNode());
766 if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
769 ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
770 if (performTrivialReplace(fragment))
773 // We can skip matching the style if the selection is plain text.
774 if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
775 && (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
776 m_matchStyle = false;
779 m_insertionStyle = EditingStyle::create(selection.start());
780 m_insertionStyle->mergeTypingStyle(document());
783 VisiblePosition visibleStart = selection.visibleStart();
784 VisiblePosition visibleEnd = selection.visibleEnd();
786 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
787 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
789 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
791 Position insertionPos = selection.start();
792 bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
793 bool selectionIsPlainText = !selection.isContentRichlyEditable();
794 Element* currentRoot = selection.rootEditableElement();
796 if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
797 startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
798 m_preventNesting = false;
800 if (selection.isRange()) {
801 // When the end of the selection being pasted into is at the end of a paragraph, and that selection
802 // spans multiple blocks, not merging may leave an empty line.
803 // When the start of the selection being pasted into is at the start of a block, not merging
804 // will leave hanging block(s).
805 // Merge blocks if the start of the selection was in a Mail blockquote, since we handle
806 // that case specially to prevent nesting.
807 bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
808 // FIXME: We should only expand to include fully selected special elements if we are copying a
809 // selection and pasting it on top of itself.
810 deleteSelection(false, mergeBlocksAfterDelete, true, false);
811 visibleStart = endingSelection().visibleStart();
812 if (fragment.hasInterchangeNewlineAtStart()) {
813 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
814 if (!isEndOfDocument(visibleStart))
815 setEndingSelection(visibleStart.next());
817 insertParagraphSeparator();
819 insertionPos = endingSelection().start();
821 ASSERT(selection.isCaret());
822 if (fragment.hasInterchangeNewlineAtStart()) {
823 VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
824 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
825 setEndingSelection(next);
827 insertParagraphSeparator();
829 // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
830 // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
831 // As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
832 // not <div>xbar<div>bar</div><div>bazx</div></div>.
833 // Don't do this if the selection started in a Mail blockquote.
834 if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
835 insertParagraphSeparator();
836 setEndingSelection(endingSelection().visibleStart().previous());
838 insertionPos = endingSelection().start();
841 // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
842 // out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case
843 // breaking the blockquote will prevent the content from actually being inserted in the table.
844 if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
845 applyCommandToComposite(BreakBlockquoteCommand::create(document()));
846 // This will leave a br between the split.
847 Node* br = endingSelection().start().deprecatedNode();
848 ASSERT(br->hasTagName(brTag));
849 // Insert content between the two blockquotes, but remove the br (since it was just a placeholder).
850 insertionPos = positionInParentBeforeNode(br);
854 // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
855 prepareWhitespaceAtPositionForSplit(insertionPos);
857 // If the downstream node has been removed there's no point in continuing.
858 if (!insertionPos.downstream().deprecatedNode())
861 // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
862 // p that maps to the same visible position as p (since in the case where a br is at the end of a block and collapsed
863 // away, there are positions after the br which map to the same visible position as [br, 0]).
864 Node* endBR = insertionPos.downstream().deprecatedNode()->hasTagName(brTag) ? insertionPos.downstream().deprecatedNode() : 0;
865 VisiblePosition originalVisPosBeforeEndBR;
867 originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
869 startBlock = enclosingBlock(insertionPos.deprecatedNode());
871 // Adjust insertionPos to prevent nesting.
872 // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
873 if (m_preventNesting && startBlock && !startIsInsideMailBlockquote) {
874 ASSERT(startBlock != currentRoot);
875 VisiblePosition visibleInsertionPos(insertionPos);
876 if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
877 insertionPos = positionInParentAfterNode(startBlock);
878 else if (isStartOfBlock(visibleInsertionPos))
879 insertionPos = positionInParentBeforeNode(startBlock);
882 // Paste at start or end of link goes outside of link.
883 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
885 // FIXME: Can this wait until after the operation has been performed? There doesn't seem to be
886 // any work performed after this that queries or uses the typing style.
887 if (Frame* frame = document()->frame())
888 frame->selection()->clearTypingStyle();
890 removeHeadContents(fragment);
892 // We don't want the destination to end up inside nodes that weren't selected. To avoid that, we move the
893 // position forward without changing the visible position so we're still at the same visible location, but
894 // outside of preceding tags.
895 insertionPos = positionAvoidingPrecedingNodes(insertionPos);
897 // Paste into run of tabs splits the tab span.
898 insertionPos = positionOutsideTabSpan(insertionPos);
900 bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
902 // If we are not trying to match the destination style we prefer a position
903 // that is outside inline elements that provide style.
904 // This way we can produce a less verbose markup.
905 // We can skip this optimization for fragments not wrapped in one of
906 // our style spans and for positions inside list items
907 // since insertAsListItems already does the right thing.
908 if (!m_matchStyle && !enclosingList(insertionPos.containerNode())) {
909 if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
910 splitTextNode(insertionPos.containerText(), insertionPos.offsetInContainerNode());
911 insertionPos = firstPositionInNode(insertionPos.containerNode());
914 if (RefPtr<Node> nodeToSplitTo = nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(insertionPos)) {
915 if (insertionPos.containerNode() != nodeToSplitTo->parentNode()) {
916 nodeToSplitTo = splitTreeToNode(insertionPos.anchorNode(), nodeToSplitTo->parentNode()).get();
917 insertionPos = positionInParentBeforeNode(nodeToSplitTo.get());
922 // FIXME: When pasting rich content we're often prevented from heading down the fast path by style spans. Try
923 // again here if they've been removed.
925 // We're finished if there is nothing to add.
926 if (fragment.isEmpty() || !fragment.firstChild())
929 // 1) Insert the content.
930 // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>.
931 // 3) Merge the start of the added content with the content before the position being pasted into.
932 // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
933 // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
934 // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
935 // incoming fragment.
936 // 5) Add spaces for smart replace.
937 // 6) Select the replacement if requested, and match style if requested.
939 InsertedNodes insertedNodes;
940 RefPtr<Node> refNode = fragment.firstChild();
941 RefPtr<Node> node = refNode->nextSibling();
943 fragment.removeNode(refNode);
945 Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
946 if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
947 && blockStart && blockStart->renderer()->isListItem())
948 refNode = insertAsListItems(refNode, blockStart, insertionPos, insertedNodes);
950 insertNodeAt(refNode, insertionPos);
951 insertedNodes.respondToNodeInsertion(refNode.get());
954 // Mutation events (bug 22634) may have already removed the inserted content
955 if (!refNode->inDocument())
958 bool plainTextFragment = isPlainTextMarkup(refNode.get());
961 RefPtr<Node> next = node->nextSibling();
962 fragment.removeNode(node.get());
963 insertNodeAfter(node, refNode.get());
964 insertedNodes.respondToNodeInsertion(node.get());
966 // Mutation events (bug 22634) may have already removed the inserted content
967 if (!node->inDocument())
971 if (node && plainTextFragment)
972 plainTextFragment = isPlainTextMarkup(node.get());
976 removeUnrenderedTextNodesAtEnds(insertedNodes);
978 if (!handledStyleSpans)
979 handleStyleSpans(insertedNodes);
981 // Mutation events (bug 20161) may have already removed the inserted content
982 if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
985 VisiblePosition startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
987 // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and
988 // didn't have a br after it, so the inserted content ended up in the same paragraph.
989 if (startBlock && insertionPos.deprecatedNode() == startBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
990 insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
992 if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) {
993 RefPtr<Node> parent = endBR->parentNode();
994 insertedNodes.willRemoveNode(endBR);
996 if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
997 insertedNodes.willRemoveNode(nodeToRemove);
998 removeNode(nodeToRemove);
1002 removeRedundantStylesAndKeepStyleSpanInline(insertedNodes);
1004 // Setup m_startOfInsertedContent and m_endOfInsertedContent. This should be the last two lines of code that access insertedNodes.
1005 m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
1006 m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
1008 // Determine whether or not we should merge the end of inserted content with what's after it before we do
1009 // the start merge so that the start merge doesn't effect our decision.
1010 m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
1012 if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
1013 VisiblePosition startOfParagraphToMove = positionAtStartOfInsertedContent();
1014 VisiblePosition destination = startOfParagraphToMove.previous();
1015 // We need to handle the case where we need to merge the end
1016 // but our destination node is inside an inline that is the last in the block.
1017 // We insert a placeholder before the newly inserted content to avoid being merged into the inline.
1018 Node* destinationNode = destination.deepEquivalent().deprecatedNode();
1019 if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
1020 insertNodeBefore(createBreakElement(document()), refNode.get());
1022 // Merging the the first paragraph of inserted content with the content that came
1023 // before the selection that was pasted into would also move content after
1024 // the selection that was pasted into if: only one paragraph was being pasted,
1025 // and it was not wrapped in a block, the selection that was pasted into ended
1026 // at the end of a block and the next paragraph didn't start at the start of a block.
1027 // Insert a line break just after the inserted content to separate it from what
1028 // comes after and prevent that from happening.
1029 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1030 if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
1031 insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
1032 // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
1033 if (!startOfParagraphToMove.deepEquivalent().anchorNode()->inDocument())
1037 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
1038 // only ever used to create positions where inserted content starts/ends.
1039 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
1040 m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent().downstream();
1041 if (m_endOfInsertedContent.isOrphan())
1042 m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent().upstream();
1045 Position lastPositionToSelect;
1046 if (fragment.hasInterchangeNewlineAtEnd()) {
1047 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1048 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
1050 if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
1051 if (!isStartOfParagraph(endOfInsertedContent)) {
1052 setEndingSelection(endOfInsertedContent);
1053 Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
1054 if (isListItem(enclosingNode)) {
1055 RefPtr<Node> newListItem = createListItemElement(document());
1056 insertNodeAfter(newListItem, enclosingNode);
1057 setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.get())));
1059 // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph
1060 // block's style seems to annoy users.
1061 insertParagraphSeparator(true);
1063 // Select up to the paragraph separator that was added.
1064 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
1065 updateNodesInserted(lastPositionToSelect.deprecatedNode());
1068 // Select up to the beginning of the next paragraph.
1069 lastPositionToSelect = next.deepEquivalent().downstream();
1075 if (Node* mailBlockquote = enclosingNodeOfType(positionAtStartOfInsertedContent().deepEquivalent(), isMailPasteAsQuotationNode))
1076 removeNodeAttribute(static_cast<Element*>(mailBlockquote), classAttr);
1078 if (shouldPerformSmartReplace())
1079 addSpacesForSmartReplace();
1081 // If we are dealing with a fragment created from plain text
1082 // no style matching is necessary.
1083 if (plainTextFragment)
1084 m_matchStyle = false;
1086 completeHTMLReplacement(lastPositionToSelect);
1089 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
1091 if (!endBR || !endBR->inDocument())
1094 VisiblePosition visiblePos(positionBeforeNode(endBR));
1096 // Don't remove the br if nothing was inserted.
1097 if (visiblePos.previous() == originalVisPosBeforeEndBR)
1100 // Remove the br if it is collapsed away and so is unnecessary.
1101 if (!document()->inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
1104 // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
1105 // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
1106 return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
1109 bool ReplaceSelectionCommand::shouldPerformSmartReplace() const
1111 if (!m_smartReplace)
1114 Element* textControl = enclosingTextFormControl(positionAtStartOfInsertedContent().deepEquivalent());
1115 if (textControl && textControl->hasTagName(inputTag) && static_cast<HTMLInputElement*>(textControl)->isPasswordField())
1116 return false; // Disable smart replace for password fields.
1121 void ReplaceSelectionCommand::addSpacesForSmartReplace()
1123 VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
1124 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1126 Position endUpstream = endOfInsertedContent.deepEquivalent().upstream();
1127 Node* endNode = endUpstream.computeNodeBeforePosition();
1128 if (endUpstream.anchorType() == Position::PositionIsOffsetInAnchor)
1129 endNode = endUpstream.containerNode();
1131 bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && !isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false);
1132 if (needsTrailingSpace && endNode) {
1133 bool collapseWhiteSpace = !endNode->renderer() || endNode->renderer()->style()->collapseWhiteSpace();
1134 if (endNode->isTextNode()) {
1135 Text* text = static_cast<Text*>(endNode);
1136 // FIXME: we shouldn't always be inserting the space at the end
1137 insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1138 if (m_endOfInsertedContent.containerNode() == text)
1139 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
1141 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1142 insertNodeAfter(node, endNode);
1143 updateNodesInserted(node.get());
1147 Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
1148 Node* startNode = startDownstream.computeNodeAfterPosition();
1149 unsigned startOffset = 0;
1150 if (startDownstream.anchorType() == Position::PositionIsOffsetInAnchor) {
1151 startNode = startDownstream.containerNode();
1152 startOffset = startDownstream.offsetInContainerNode();
1155 bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && !isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true);
1156 if (needsLeadingSpace && startNode) {
1157 bool collapseWhiteSpace = !startNode->renderer() || startNode->renderer()->style()->collapseWhiteSpace();
1158 if (startNode->isTextNode()) {
1159 insertTextIntoNode(static_cast<Text*>(startNode), startOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1160 if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
1161 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
1163 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1164 // Don't updateNodesInserted. Doing so would set m_endOfInsertedContent to be the node containing the leading space,
1165 // but m_endOfInsertedContent is supposed to mark the end of pasted content.
1166 insertNodeBefore(node, startNode);
1167 m_startOfInsertedContent = firstPositionInNode(node.get());
1172 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
1174 Position start = positionAtStartOfInsertedContent().deepEquivalent();
1175 Position end = positionAtEndOfInsertedContent().deepEquivalent();
1177 // Mutation events may have deleted start or end
1178 if (start.isNotNull() && !start.isOrphan() && end.isNotNull() && !end.isOrphan()) {
1179 // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
1180 rebalanceWhitespaceAt(start);
1181 rebalanceWhitespaceAt(end);
1184 ASSERT(m_insertionStyle);
1185 applyStyle(m_insertionStyle.get(), start, end);
1188 if (lastPositionToSelect.isNotNull())
1189 end = lastPositionToSelect;
1190 } else if (lastPositionToSelect.isNotNull())
1191 start = end = lastPositionToSelect;
1195 if (m_selectReplacement)
1196 setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1198 setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1201 EditAction ReplaceSelectionCommand::editingAction() const
1203 return m_editAction;
1206 // If the user is inserting a list into an existing list, instead of nesting the list,
1207 // we put the list items into the existing list.
1208 Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<Node> prpListElement, Node* insertionBlock, const Position& insertPos, InsertedNodes& insertedNodes)
1210 RefPtr<Node> listElement = prpListElement;
1212 while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1)
1213 listElement = listElement->firstChild();
1215 bool isStart = isStartOfParagraph(insertPos);
1216 bool isEnd = isEndOfParagraph(insertPos);
1217 bool isMiddle = !isStart && !isEnd;
1218 Node* lastNode = insertionBlock;
1220 // If we're in the middle of a list item, we should split it into two separate
1221 // list items and insert these nodes between them.
1223 int textNodeOffset = insertPos.offsetInContainerNode();
1224 if (insertPos.deprecatedNode()->isTextNode() && textNodeOffset > 0)
1225 splitTextNode(static_cast<Text*>(insertPos.deprecatedNode()), textNodeOffset);
1226 splitTreeToNode(insertPos.deprecatedNode(), lastNode, true);
1229 while (RefPtr<Node> listItem = listElement->firstChild()) {
1230 ExceptionCode ec = 0;
1231 toContainerNode(listElement.get())->removeChild(listItem.get(), ec);
1233 if (isStart || isMiddle) {
1234 insertNodeBefore(listItem, lastNode);
1235 insertedNodes.respondToNodeInsertion(listItem.get());
1237 insertNodeAfter(listItem, lastNode);
1238 insertedNodes.respondToNodeInsertion(listItem.get());
1239 lastNode = listItem.get();
1241 ASSERT_NOT_REACHED();
1243 if (isStart || isMiddle)
1244 lastNode = lastNode->previousSibling();
1246 insertNodeAfter(createListItemElement(document()), lastNode);
1250 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
1255 if (m_startOfInsertedContent.isNull())
1256 m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
1258 m_endOfInsertedContent = lastPositionInOrAfterNode(node->lastDescendant());
1261 // During simple pastes, where we're just pasting a text node into a run of text, we insert the text node
1262 // directly into the text node that holds the selection. This is much faster than the generalized code in
1263 // ReplaceSelectionCommand, and works around <https://bugs.webkit.org/show_bug.cgi?id=6148> since we don't
1264 // split text nodes.
1265 bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
1267 if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
1270 // FIXME: Would be nice to handle smart replace in the fast path.
1271 if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
1274 // e.g. when "bar" is inserted after "foo" in <div><u>foo</u></div>, "bar" should not be underlined.
1275 if (nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(endingSelection().start()))
1278 Node* nodeAfterInsertionPos = endingSelection().end().downstream().anchorNode();
1279 Text* textNode = static_cast<Text*>(fragment.firstChild());
1280 // Our fragment creation code handles tabs, spaces, and newlines, so we don't have to worry about those here.
1282 Position start = endingSelection().start();
1283 Position end = replaceSelectedTextInNode(textNode->data());
1287 if (nodeAfterInsertionPos && nodeAfterInsertionPos->hasTagName(brTag) && shouldRemoveEndBR(nodeAfterInsertionPos, positionBeforeNode(nodeAfterInsertionPos)))
1288 removeNodeAndPruneAncestors(nodeAfterInsertionPos);
1290 VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
1292 setEndingSelection(selectionAfterReplace);
1297 } // namespace WebCore