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 "core/editing/ReplaceSelectionCommand.h"
30 #include "CSSPropertyNames.h"
31 #include "HTMLNames.h"
32 #include "bindings/v8/ExceptionStatePlaceholder.h"
33 #include "core/css/CSSStyleDeclaration.h"
34 #include "core/css/StylePropertySet.h"
35 #include "core/dom/Document.h"
36 #include "core/dom/DocumentFragment.h"
37 #include "core/dom/Element.h"
38 #include "core/dom/Text.h"
39 #include "core/editing/ApplyStyleCommand.h"
40 #include "core/editing/BreakBlockquoteCommand.h"
41 #include "core/editing/FrameSelection.h"
42 #include "core/editing/HTMLInterchange.h"
43 #include "core/editing/SimplifyMarkupCommand.h"
44 #include "core/editing/SmartReplace.h"
45 #include "core/editing/TextIterator.h"
46 #include "core/editing/VisibleUnits.h"
47 #include "core/editing/htmlediting.h"
48 #include "core/editing/markup.h"
49 #include "core/events/BeforeTextInsertedEvent.h"
50 #include "core/events/ThreadLocalEventNames.h"
51 #include "core/html/HTMLElement.h"
52 #include "core/html/HTMLInputElement.h"
53 #include "core/frame/Frame.h"
54 #include "core/rendering/RenderObject.h"
55 #include "core/rendering/RenderText.h"
56 #include "wtf/StdLibExtras.h"
57 #include "wtf/Vector.h"
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*, 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(PassRefPtr<Node>);
84 PassRefPtr<Element> insertFragmentForTestRendering(Node* rootEditableNode);
85 void removeUnrenderedNodes(Node*);
86 void restoreAndRemoveTestRenderingNodesToFragment(Element*);
87 void removeInterchangeNodes(Node*);
89 void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
91 RefPtr<Document> m_document;
92 RefPtr<DocumentFragment> m_fragment;
93 bool m_hasInterchangeNewlineAtStart;
94 bool m_hasInterchangeNewlineAtEnd;
97 static bool isInterchangeNewlineNode(const Node *node)
99 DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
100 return node && node->hasTagName(brTag) && toElement(node)->getAttribute(classAttr) == interchangeNewlineClassString;
103 static bool isInterchangeConvertedSpaceSpan(const Node *node)
105 DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
106 return node->isHTMLElement() && toHTMLElement(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
109 static Position positionAvoidingPrecedingNodes(Position pos)
111 // If we're already on a break, it's probably a placeholder and we shouldn't change our position.
112 if (editingIgnoresContent(pos.deprecatedNode()))
115 // We also stop when changing block flow elements because even though the visual position is the
118 // The two positions above are the same visual position, but we want to stay in the same block.
119 Node* enclosingBlockNode = enclosingBlock(pos.containerNode());
120 for (Position nextPosition = pos; nextPosition.containerNode() != enclosingBlockNode; pos = nextPosition) {
121 if (lineBreakExistsAtPosition(pos))
124 if (pos.containerNode()->nonShadowBoundaryParentNode())
125 nextPosition = positionInParentAfterNode(pos.containerNode());
127 if (nextPosition == pos
128 || enclosingBlock(nextPosition.containerNode()) != enclosingBlockNode
129 || VisiblePosition(pos) != VisiblePosition(nextPosition))
135 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, const VisibleSelection& selection)
136 : m_document(document),
137 m_fragment(fragment),
138 m_hasInterchangeNewlineAtStart(false),
139 m_hasInterchangeNewlineAtEnd(false)
145 if (!m_fragment->firstChild())
148 RefPtr<Element> editableRoot = selection.rootEditableElement();
149 ASSERT(editableRoot);
153 Node* shadowAncestorNode = editableRoot->deprecatedShadowAncestorNode();
155 if (!editableRoot->getAttributeEventListener(EventTypeNames::webkitBeforeTextInserted) &&
156 // FIXME: Remove these checks once textareas and textfields actually register an event handler.
157 !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
158 editableRoot->rendererIsRichlyEditable()) {
159 removeInterchangeNodes(m_fragment.get());
163 RefPtr<Element> holder = insertFragmentForTestRendering(editableRoot.get());
165 removeInterchangeNodes(m_fragment.get());
169 RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
170 String text = plainText(range.get(), static_cast<TextIteratorBehavior>(TextIteratorEmitsOriginalText | TextIteratorIgnoresStyleVisibility));
172 removeInterchangeNodes(holder.get());
173 removeUnrenderedNodes(holder.get());
174 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
176 // Give the root a chance to change the text.
177 RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
178 editableRoot->dispatchEvent(evt, ASSERT_NO_EXCEPTION);
179 if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
180 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
182 m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
183 if (!m_fragment->firstChild())
186 holder = insertFragmentForTestRendering(editableRoot.get());
187 removeInterchangeNodes(holder.get());
188 removeUnrenderedNodes(holder.get());
189 restoreAndRemoveTestRenderingNodesToFragment(holder.get());
193 bool ReplacementFragment::isEmpty() const
195 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
198 Node *ReplacementFragment::firstChild() const
200 return m_fragment ? m_fragment->firstChild() : 0;
203 Node *ReplacementFragment::lastChild() const
205 return m_fragment ? m_fragment->lastChild() : 0;
208 void ReplacementFragment::removeNodePreservingChildren(PassRefPtr<Node> node)
213 while (RefPtr<Node> n = node->firstChild()) {
215 insertNodeBefore(n.release(), node.get());
220 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
225 ContainerNode* parent = node->nonShadowBoundaryParentNode();
229 parent->removeChild(node.get());
232 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
234 if (!node || !refNode)
237 ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
241 parent->insertBefore(node, refNode);
244 PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
247 RefPtr<Element> holder = createDefaultParagraphElement(*m_document.get());
249 holder->appendChild(m_fragment);
250 rootEditableElement->appendChild(holder.get());
251 m_document->updateLayoutIgnorePendingStylesheets();
253 return holder.release();
256 void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(Element* holder)
261 while (RefPtr<Node> node = holder->firstChild()) {
262 holder->removeChild(node.get());
263 m_fragment->appendChild(node.get());
269 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
271 Vector<RefPtr<Node> > unrendered;
273 for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder))
274 if (!isNodeRendered(node) && !isTableStructureNode(node))
275 unrendered.append(node);
277 size_t n = unrendered.size();
278 for (size_t i = 0; i < n; ++i)
279 removeNode(unrendered[i]);
282 void ReplacementFragment::removeInterchangeNodes(Node* container)
284 m_hasInterchangeNewlineAtStart = false;
285 m_hasInterchangeNewlineAtEnd = false;
287 // Interchange newlines at the "start" of the incoming fragment must be
288 // either the first node in the fragment or the first leaf in the fragment.
289 Node* node = container->firstChild();
291 if (isInterchangeNewlineNode(node)) {
292 m_hasInterchangeNewlineAtStart = true;
296 node = node->firstChild();
298 if (!container->hasChildNodes())
300 // Interchange newlines at the "end" of the incoming fragment must be
301 // either the last node in the fragment or the last leaf in the fragment.
302 node = container->lastChild();
304 if (isInterchangeNewlineNode(node)) {
305 m_hasInterchangeNewlineAtEnd = true;
309 node = node->lastChild();
312 node = container->firstChild();
314 RefPtr<Node> next = NodeTraversal::next(*node);
315 if (isInterchangeConvertedSpaceSpan(node)) {
316 next = NodeTraversal::nextSkippingChildren(*node);
317 removeNodePreservingChildren(node);
323 inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node& node)
325 if (!m_firstNodeInserted)
326 m_firstNodeInserted = &node;
328 m_lastNodeInserted = &node;
331 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node& node)
333 if (m_firstNodeInserted == node)
334 m_firstNodeInserted = NodeTraversal::next(node);
335 if (m_lastNodeInserted == node)
336 m_lastNodeInserted = node.lastChild() ? node.lastChild() : NodeTraversal::nextSkippingChildren(node);
339 inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node& node)
341 if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
342 m_firstNodeInserted = 0;
343 m_lastNodeInserted = 0;
344 } else if (m_firstNodeInserted == node) {
345 m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
346 } else if (m_lastNodeInserted == node) {
347 m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
351 inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node& node, Node& newNode)
353 if (m_firstNodeInserted == node)
354 m_firstNodeInserted = &newNode;
355 if (m_lastNodeInserted == node)
356 m_lastNodeInserted = &newNode;
359 ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
360 : CompositeEditCommand(document)
361 , m_selectReplacement(options & SelectReplacement)
362 , m_smartReplace(options & SmartReplace)
363 , m_matchStyle(options & MatchStyle)
364 , m_documentFragment(fragment)
365 , m_preventNesting(options & PreventNesting)
366 , m_movingParagraph(options & MovingParagraph)
367 , m_editAction(editAction)
368 , m_sanitizeFragment(options & SanitizeFragment)
369 , m_shouldMergeEnd(false)
373 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
375 Position existing = endOfExistingContent.deepEquivalent();
376 Position inserted = endOfInsertedContent.deepEquivalent();
377 bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
378 return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
381 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
383 if (m_movingParagraph)
386 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
387 VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
391 // When we have matching quote levels, its ok to merge more frequently.
392 // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
393 // And we should only merge here if the selection start was inside a mail blockquote. This prevents against removing a
394 // blockquote from newly pasted quoted content that was pasted into an unquoted position. If that unquoted position happens
395 // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
396 if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
399 return !selectionStartWasStartOfParagraph
400 && !fragmentHasInterchangeNewlineAtStart
401 && isStartOfParagraph(startOfInsertedContent)
402 && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
403 && shouldMerge(startOfInsertedContent, prev);
406 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
408 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
409 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
413 return !selectionEndWasEndOfParagraph
414 && isEndOfParagraph(endOfInsertedContent)
415 && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
416 && shouldMerge(endOfInsertedContent, next);
419 static bool isMailPasteAsQuotationNode(const Node* node)
421 return node && node->hasTagName(blockquoteTag) && node->isElementNode() && toElement(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
424 static bool isHeaderElement(const Node* a)
429 return a->hasTagName(h1Tag)
430 || a->hasTagName(h2Tag)
431 || a->hasTagName(h3Tag)
432 || a->hasTagName(h4Tag)
433 || a->hasTagName(h5Tag)
434 || a->hasTagName(h6Tag);
437 static bool haveSameTagName(Node* a, Node* b)
439 return a && b && a->isElementNode() && b->isElementNode() && toElement(a)->tagName() == toElement(b)->tagName();
442 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
444 if (source.isNull() || destination.isNull())
447 Node* sourceNode = source.deepEquivalent().deprecatedNode();
448 Node* destinationNode = destination.deepEquivalent().deprecatedNode();
449 Node* sourceBlock = enclosingBlock(sourceNode);
450 Node* destinationBlock = enclosingBlock(destinationNode);
451 return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
452 sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) &&
453 enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
454 enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
455 (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
456 // Don't merge to or from a position before or after a block because it would
457 // be a no-op and cause infinite recursion.
458 !isBlock(sourceNode) && !isBlock(destinationNode);
461 // Style rules that match just inserted elements could change their appearance, like
462 // a div inserted into a document with div { display:inline; }.
463 void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
465 RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
467 for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
468 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
470 next = NodeTraversal::next(*node);
471 if (!node->isStyledElement())
474 Element* element = toElement(node);
476 const StylePropertySet* inlineStyle = element->inlineStyle();
477 RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
479 if (element->isHTMLElement()) {
480 Vector<QualifiedName> attributes;
481 HTMLElement* htmlElement = toHTMLElement(element);
484 if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
485 // e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
486 node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
487 element = toElement(node);
488 insertedNodes.didReplaceNode(*htmlElement, *node);
489 } else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
490 EditingStyle::DoNotExtractMatchingStyle)) {
491 // e.g. <font size="3" style="font-size: 20px;"> is converted to <font style="font-size: 20px;">
492 for (size_t i = 0; i < attributes.size(); i++)
493 removeNodeAttribute(element, attributes[i]);
497 ContainerNode* context = element->parentNode();
499 // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
500 // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
501 Node* blockquoteNode = !context || isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
503 newInlineStyle->removeStyleFromRulesAndContext(element, document().documentElement());
505 newInlineStyle->removeStyleFromRulesAndContext(element, context);
508 if (!inlineStyle || newInlineStyle->isEmpty()) {
509 if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
510 insertedNodes.willRemoveNodePreservingChildren(*element);
511 removeNodePreservingChildren(element);
514 removeNodeAttribute(element, styleAttr);
515 } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount()) {
516 setNodeAttribute(element, styleAttr, AtomicString(newInlineStyle->style()->asText()));
519 // FIXME: Tolerate differences in id, class, and style attributes.
520 if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
521 && VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
522 && VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
523 insertedNodes.willRemoveNodePreservingChildren(*element);
524 removeNodePreservingChildren(element);
528 if (element->parentNode() && element->parentNode()->rendererIsRichlyEditable())
529 removeNodeAttribute(element, contenteditableAttr);
531 // WebKit used to not add display: inline and float: none on copy.
532 // Keep this code around for backward compatibility
533 if (isLegacyAppleStyleSpan(element)) {
534 if (!element->firstChild()) {
535 insertedNodes.willRemoveNodePreservingChildren(*element);
536 removeNodePreservingChildren(element);
539 // There are other styles that style rules can give to style spans,
540 // but these are the two important ones because they'll prevent
541 // inserted content from appearing in the right paragraph.
542 // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
543 // results. We already know one issue because td elements ignore their display property
544 // in quirks mode (which Mail.app is always in). We should look for an alternative.
546 // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
547 if (isBlock(element))
548 element->style()->setPropertyInternal(CSSPropertyDisplay, "inline", false, IGNORE_EXCEPTION);
549 if (element->renderer() && element->renderer()->style()->isFloating())
550 element->style()->setPropertyInternal(CSSPropertyFloat, "none", false, IGNORE_EXCEPTION);
555 static bool isProhibitedParagraphChild(const AtomicString& name)
557 // https://dvcs.w3.org/hg/editing/raw-file/57abe6d3cb60/editing.html#prohibited-paragraph-child
558 DEFINE_STATIC_LOCAL(HashSet<AtomicString>, elements, ());
559 if (elements.isEmpty()) {
560 elements.add(addressTag.localName());
561 elements.add(articleTag.localName());
562 elements.add(asideTag.localName());
563 elements.add(blockquoteTag.localName());
564 elements.add(captionTag.localName());
565 elements.add(centerTag.localName());
566 elements.add(colTag.localName());
567 elements.add(colgroupTag.localName());
568 elements.add(ddTag.localName());
569 elements.add(detailsTag.localName());
570 elements.add(dirTag.localName());
571 elements.add(divTag.localName());
572 elements.add(dlTag.localName());
573 elements.add(dtTag.localName());
574 elements.add(fieldsetTag.localName());
575 elements.add(figcaptionTag.localName());
576 elements.add(figureTag.localName());
577 elements.add(footerTag.localName());
578 elements.add(formTag.localName());
579 elements.add(h1Tag.localName());
580 elements.add(h2Tag.localName());
581 elements.add(h3Tag.localName());
582 elements.add(h4Tag.localName());
583 elements.add(h5Tag.localName());
584 elements.add(h6Tag.localName());
585 elements.add(headerTag.localName());
586 elements.add(hgroupTag.localName());
587 elements.add(hrTag.localName());
588 elements.add(liTag.localName());
589 elements.add(listingTag.localName());
590 elements.add(mainTag.localName()); // Missing in the specification.
591 elements.add(menuTag.localName());
592 elements.add(navTag.localName());
593 elements.add(olTag.localName());
594 elements.add(pTag.localName());
595 elements.add(plaintextTag.localName());
596 elements.add(preTag.localName());
597 elements.add(sectionTag.localName());
598 elements.add(summaryTag.localName());
599 elements.add(tableTag.localName());
600 elements.add(tbodyTag.localName());
601 elements.add(tdTag.localName());
602 elements.add(tfootTag.localName());
603 elements.add(thTag.localName());
604 elements.add(theadTag.localName());
605 elements.add(trTag.localName());
606 elements.add(ulTag.localName());
607 elements.add(xmpTag.localName());
609 return elements.contains(name);
612 void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
614 RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
616 for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
617 next = NodeTraversal::next(*node);
619 if (!node->isHTMLElement())
622 if (isProhibitedParagraphChild(toHTMLElement(node)->localName())) {
623 if (HTMLElement* paragraphElement = toHTMLElement(enclosingNodeWithTag(positionInParentBeforeNode(node.get()), pTag)))
624 moveNodeOutOfAncestor(node, paragraphElement);
627 if (isHeaderElement(node.get())) {
628 if (HTMLElement* headerElement = toHTMLElement(highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement)))
629 moveNodeOutOfAncestor(node, headerElement);
634 void ReplaceSelectionCommand::moveNodeOutOfAncestor(PassRefPtr<Node> prpNode, PassRefPtr<Node> prpAncestor)
636 RefPtr<Node> node = prpNode;
637 RefPtr<Node> ancestor = prpAncestor;
639 if (!ancestor->parentNode()->rendererIsEditable())
642 VisiblePosition positionAtEndOfNode = lastPositionInOrAfterNode(node.get());
643 VisiblePosition lastPositionInParagraph = lastPositionInNode(ancestor.get());
644 if (positionAtEndOfNode == lastPositionInParagraph) {
646 if (ancestor->nextSibling())
647 insertNodeBefore(node, ancestor->nextSibling());
649 appendNode(node, ancestor->parentNode());
651 RefPtr<Node> nodeToSplitTo = splitTreeToNode(node.get(), ancestor.get(), true);
653 insertNodeBefore(node, nodeToSplitTo);
655 if (!ancestor->firstChild())
656 removeNode(ancestor.release());
659 static inline bool nodeHasVisibleRenderText(Text& text)
661 return text.renderer() && toRenderText(text.renderer())->renderedTextLength() > 0;
664 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
666 document().updateLayoutIgnorePendingStylesheets();
668 Node* lastLeafInserted = insertedNodes.lastLeafInserted();
669 if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*lastLeafInserted))
670 && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
671 && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
672 insertedNodes.willRemoveNode(*lastLeafInserted);
673 removeNode(lastLeafInserted);
676 // We don't have to make sure that firstNodeInserted isn't inside a select or script element, because
677 // it is a top level node in the fragment and the user can't insert into those elements.
678 Node* firstNodeInserted = insertedNodes.firstNodeInserted();
679 if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*firstNodeInserted))) {
680 insertedNodes.willRemoveNode(*firstNodeInserted);
681 removeNode(firstNodeInserted);
685 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
687 // FIXME: Why is this hack here? What's special about <select> tags?
688 Node* enclosingSelect = enclosingNodeWithTag(m_endOfInsertedContent, selectTag);
689 return enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent;
692 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
694 return m_startOfInsertedContent;
697 static void removeHeadContents(ReplacementFragment& fragment)
700 for (Node* node = fragment.firstChild(); node; node = next) {
701 if (node->hasTagName(baseTag)
702 || node->hasTagName(linkTag)
703 || node->hasTagName(metaTag)
704 || node->hasTagName(styleTag)
705 || node->hasTagName(titleTag)) {
706 next = NodeTraversal::nextSkippingChildren(*node);
707 fragment.removeNode(node);
709 next = NodeTraversal::next(*node);
714 // Remove style spans before insertion if they are unnecessary. It's faster because we'll
715 // avoid doing a layout.
716 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
718 Node* topNode = fragment.firstChild();
720 // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
721 // and doesn't receive the optimization.
722 if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
725 // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
726 // before inserting it. Look for and handle style spans after insertion.
727 if (!isLegacyAppleStyleSpan(topNode))
730 Node* wrappingStyleSpan = topNode;
731 RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
732 String styleText = styleAtInsertionPos->style()->asText();
734 // FIXME: This string comparison is a naive way of comparing two styles.
735 // We should be taking the diff and check that the diff is empty.
736 if (styleText != toElement(wrappingStyleSpan)->getAttribute(styleAttr))
739 fragment.removeNodePreservingChildren(wrappingStyleSpan);
743 // At copy time, WebKit wraps copied content in a span that contains the source document's
744 // default styles. If the copied Range inherits any other styles from its ancestors, we put
745 // those styles on a second span.
746 // This function removes redundant styles from those spans, and removes the spans if all their
747 // styles are redundant.
748 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
749 // We should remove styles from spans that are overridden by all of their children, either here
751 void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
753 HTMLElement* wrappingStyleSpan = 0;
754 // The style span that contains the source document's default style should be at
755 // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
756 // so search for the top level style span instead of assuming it's at the top.
757 for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
758 if (isLegacyAppleStyleSpan(node)) {
759 wrappingStyleSpan = toHTMLElement(node);
764 // There might not be any style spans if we're pasting from another application or if
765 // we are here because of a document.execCommand("InsertHTML", ...) call.
766 if (!wrappingStyleSpan)
769 RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->inlineStyle());
770 ContainerNode* context = wrappingStyleSpan->parentNode();
772 // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
773 // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
774 Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
776 context = document().documentElement();
778 // This operation requires that only editing styles to be removed from sourceDocumentStyle.
779 style->prepareToApplyAt(firstPositionInNode(context));
781 // Remove block properties in the span's style. This prevents properties that probably have no effect
782 // currently from affecting blocks later if the style is cloned for a new block element during a future
783 // editing operation.
784 // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
785 // with block styles by the editing engine used to style them. WebKit doesn't do this, but others might.
786 style->removeBlockProperties();
788 if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
789 insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
790 removeNodePreservingChildren(wrappingStyleSpan);
792 setNodeAttribute(wrappingStyleSpan, styleAttr, AtomicString(style->style()->asText()));
796 void ReplaceSelectionCommand::mergeEndIfNeeded()
798 if (!m_shouldMergeEnd)
801 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
802 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
804 // Bail to avoid infinite recursion.
805 if (m_movingParagraph) {
806 ASSERT_NOT_REACHED();
810 // Merging two paragraphs will destroy the moved one's block styles. Always move the end of inserted forward
811 // to preserve the block style of the paragraph already in the document, unless the paragraph to move would
812 // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
814 bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
816 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
817 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
819 // Merging forward could result in deleting the destination anchor node.
820 // To avoid this, we add a placeholder node before the start of the paragraph.
821 if (endOfParagraph(startOfParagraphToMove) == destination) {
822 RefPtr<Node> placeholder = createBreakElement(document());
823 insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
824 destination = VisiblePosition(positionBeforeNode(placeholder.get()));
827 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
829 // Merging forward will remove m_endOfInsertedContent from the document.
831 if (m_startOfInsertedContent.isOrphan())
832 m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
833 m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
834 // If we merged text nodes, m_endOfInsertedContent could be null. If this is the case, we use m_startOfInsertedContent.
835 if (m_endOfInsertedContent.isNull())
836 m_endOfInsertedContent = m_startOfInsertedContent;
840 static Node* enclosingInline(Node* node)
842 while (ContainerNode* parent = node->parentNode()) {
843 if (parent->isBlockFlowElement() || parent->hasTagName(bodyTag))
845 // Stop if any previous sibling is a block.
846 for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
847 if (sibling->isBlockFlowElement())
855 static bool isInlineNodeWithStyle(const Node* node)
857 // We don't want to skip over any block elements.
861 if (!node->isHTMLElement())
864 // We can skip over elements whose class attribute is
865 // one of our internal classes.
866 const HTMLElement* element = toHTMLElement(node);
867 const AtomicString& classAttributeValue = element->getAttribute(classAttr);
868 if (classAttributeValue == AppleTabSpanClass
869 || classAttributeValue == AppleConvertedSpace
870 || classAttributeValue == ApplePasteAsQuotation)
873 return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
876 inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
878 Node* containgBlock = enclosingBlock(insertionPos.containerNode());
879 return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
882 void ReplaceSelectionCommand::doApply()
884 VisibleSelection selection = endingSelection();
885 ASSERT(selection.isCaretOrRange());
886 ASSERT(selection.start().deprecatedNode());
887 if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
890 if (!selection.rootEditableElement())
893 ReplacementFragment fragment(&document(), m_documentFragment.get(), selection);
894 if (performTrivialReplace(fragment))
897 // We can skip matching the style if the selection is plain text.
898 if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
899 && (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
900 m_matchStyle = false;
903 m_insertionStyle = EditingStyle::create(selection.start());
904 m_insertionStyle->mergeTypingStyle(&document());
907 VisiblePosition visibleStart = selection.visibleStart();
908 VisiblePosition visibleEnd = selection.visibleEnd();
910 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
911 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
913 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
915 Position insertionPos = selection.start();
916 bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
917 bool selectionIsPlainText = !selection.isContentRichlyEditable();
918 Element* currentRoot = selection.rootEditableElement();
920 if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
921 startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
922 m_preventNesting = false;
924 if (selection.isRange()) {
925 // When the end of the selection being pasted into is at the end of a paragraph, and that selection
926 // spans multiple blocks, not merging may leave an empty line.
927 // When the start of the selection being pasted into is at the start of a block, not merging
928 // will leave hanging block(s).
929 // Merge blocks if the start of the selection was in a Mail blockquote, since we handle
930 // that case specially to prevent nesting.
931 bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
932 // FIXME: We should only expand to include fully selected special elements if we are copying a
933 // selection and pasting it on top of itself.
934 deleteSelection(false, mergeBlocksAfterDelete, false);
935 visibleStart = endingSelection().visibleStart();
936 if (fragment.hasInterchangeNewlineAtStart()) {
937 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
938 if (!isEndOfEditableOrNonEditableContent(visibleStart))
939 setEndingSelection(visibleStart.next());
941 insertParagraphSeparator();
943 insertionPos = endingSelection().start();
945 ASSERT(selection.isCaret());
946 if (fragment.hasInterchangeNewlineAtStart()) {
947 VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
948 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
949 setEndingSelection(next);
951 insertParagraphSeparator();
952 visibleStart = endingSelection().visibleStart();
955 // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
956 // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
957 // As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
958 // not <div>xbar<div>bar</div><div>bazx</div></div>.
959 // Don't do this if the selection started in a Mail blockquote.
960 if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
961 insertParagraphSeparator();
962 setEndingSelection(endingSelection().visibleStart().previous());
964 insertionPos = endingSelection().start();
967 // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
968 // out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case
969 // breaking the blockquote will prevent the content from actually being inserted in the table.
970 if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
971 applyCommandToComposite(BreakBlockquoteCommand::create(document()));
972 // This will leave a br between the split.
973 Node* br = endingSelection().start().deprecatedNode();
974 ASSERT(br->hasTagName(brTag));
975 // Insert content between the two blockquotes, but remove the br (since it was just a placeholder).
976 insertionPos = positionInParentBeforeNode(br);
980 // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
981 prepareWhitespaceAtPositionForSplit(insertionPos);
983 // If the downstream node has been removed there's no point in continuing.
984 if (!insertionPos.downstream().deprecatedNode())
987 // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
988 // 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
989 // away, there are positions after the br which map to the same visible position as [br, 0]).
990 Node* endBR = insertionPos.downstream().deprecatedNode()->hasTagName(brTag) ? insertionPos.downstream().deprecatedNode() : 0;
991 VisiblePosition originalVisPosBeforeEndBR;
993 originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
995 RefPtr<Node> insertionBlock = enclosingBlock(insertionPos.deprecatedNode());
997 // Adjust insertionPos to prevent nesting.
998 // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
999 if (m_preventNesting && insertionBlock && !isTableCell(insertionBlock.get()) && !startIsInsideMailBlockquote) {
1000 ASSERT(insertionBlock != currentRoot);
1001 VisiblePosition visibleInsertionPos(insertionPos);
1002 if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
1003 insertionPos = positionInParentAfterNode(insertionBlock.get());
1004 else if (isStartOfBlock(visibleInsertionPos))
1005 insertionPos = positionInParentBeforeNode(insertionBlock.get());
1008 // Paste at start or end of link goes outside of link.
1009 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
1011 // FIXME: Can this wait until after the operation has been performed? There doesn't seem to be
1012 // any work performed after this that queries or uses the typing style.
1013 if (Frame* frame = document().frame())
1014 frame->selection().clearTypingStyle();
1016 removeHeadContents(fragment);
1018 // We don't want the destination to end up inside nodes that weren't selected. To avoid that, we move the
1019 // position forward without changing the visible position so we're still at the same visible location, but
1020 // outside of preceding tags.
1021 insertionPos = positionAvoidingPrecedingNodes(insertionPos);
1023 // Paste into run of tabs splits the tab span.
1024 insertionPos = positionOutsideTabSpan(insertionPos);
1026 bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
1028 // We're finished if there is nothing to add.
1029 if (fragment.isEmpty() || !fragment.firstChild())
1032 // If we are not trying to match the destination style we prefer a position
1033 // that is outside inline elements that provide style.
1034 // This way we can produce a less verbose markup.
1035 // We can skip this optimization for fragments not wrapped in one of
1036 // our style spans and for positions inside list items
1037 // since insertAsListItems already does the right thing.
1038 if (!m_matchStyle && !enclosingList(insertionPos.containerNode())) {
1039 if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
1040 splitTextNode(insertionPos.containerText(), insertionPos.offsetInContainerNode());
1041 insertionPos = firstPositionInNode(insertionPos.containerNode());
1044 if (RefPtr<Node> nodeToSplitTo = nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(insertionPos)) {
1045 if (insertionPos.containerNode() != nodeToSplitTo->parentNode()) {
1046 Node* splitStart = insertionPos.computeNodeAfterPosition();
1048 splitStart = insertionPos.containerNode();
1049 nodeToSplitTo = splitTreeToNode(splitStart, nodeToSplitTo->parentNode()).get();
1050 insertionPos = positionInParentBeforeNode(nodeToSplitTo.get());
1055 // FIXME: When pasting rich content we're often prevented from heading down the fast path by style spans. Try
1056 // again here if they've been removed.
1058 // 1) Insert the content.
1059 // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>.
1060 // 3) Merge the start of the added content with the content before the position being pasted into.
1061 // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
1062 // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
1063 // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
1064 // incoming fragment.
1065 // 5) Add spaces for smart replace.
1066 // 6) Select the replacement if requested, and match style if requested.
1068 InsertedNodes insertedNodes;
1069 RefPtr<Node> refNode = fragment.firstChild();
1071 RefPtr<Node> node = refNode->nextSibling();
1073 fragment.removeNode(refNode);
1075 Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
1076 if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
1077 && blockStart && blockStart->renderer()->isListItem())
1078 refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
1080 insertNodeAt(refNode, insertionPos);
1081 insertedNodes.respondToNodeInsertion(*refNode);
1084 // Mutation events (bug 22634) may have already removed the inserted content
1085 if (!refNode->inDocument())
1088 bool plainTextFragment = isPlainTextMarkup(refNode.get());
1091 RefPtr<Node> next = node->nextSibling();
1092 fragment.removeNode(node.get());
1093 insertNodeAfter(node, refNode);
1094 insertedNodes.respondToNodeInsertion(*node);
1096 // Mutation events (bug 22634) may have already removed the inserted content
1097 if (!node->inDocument())
1101 if (node && plainTextFragment)
1102 plainTextFragment = isPlainTextMarkup(node.get());
1106 removeUnrenderedTextNodesAtEnds(insertedNodes);
1108 if (!handledStyleSpans)
1109 handleStyleSpans(insertedNodes);
1111 // Mutation events (bug 20161) may have already removed the inserted content
1112 if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
1115 // Scripts specified in javascript protocol may remove |insertionBlock|
1116 // during insertion, e.g. <iframe src="javascript:...">
1117 if (insertionBlock && !insertionBlock->inDocument())
1120 VisiblePosition startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
1122 // We inserted before the insertionBlock to prevent nesting, and the content before the insertionBlock wasn't in its own block and
1123 // didn't have a br after it, so the inserted content ended up in the same paragraph.
1124 if (insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
1125 insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
1127 if (endBR && (plainTextFragment || (shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR) && !(fragment.hasInterchangeNewlineAtEnd() && selectionIsPlainText)))) {
1128 RefPtr<Node> parent = endBR->parentNode();
1129 insertedNodes.willRemoveNode(*endBR);
1131 if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
1132 insertedNodes.willRemoveNode(*nodeToRemove);
1133 removeNode(nodeToRemove);
1137 makeInsertedContentRoundTrippableWithHTMLTreeBuilder(insertedNodes);
1139 removeRedundantStylesAndKeepStyleSpanInline(insertedNodes);
1141 if (m_sanitizeFragment)
1142 applyCommandToComposite(SimplifyMarkupCommand::create(document(), insertedNodes.firstNodeInserted(), insertedNodes.pastLastLeaf()));
1144 // Setup m_startOfInsertedContent and m_endOfInsertedContent. This should be the last two lines of code that access insertedNodes.
1145 m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
1146 m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
1148 // Determine whether or not we should merge the end of inserted content with what's after it before we do
1149 // the start merge so that the start merge doesn't effect our decision.
1150 m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
1152 if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
1153 VisiblePosition startOfParagraphToMove = positionAtStartOfInsertedContent();
1154 VisiblePosition destination = startOfParagraphToMove.previous();
1155 // We need to handle the case where we need to merge the end
1156 // but our destination node is inside an inline that is the last in the block.
1157 // We insert a placeholder before the newly inserted content to avoid being merged into the inline.
1158 Node* destinationNode = destination.deepEquivalent().deprecatedNode();
1159 if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
1160 insertNodeBefore(createBreakElement(document()), refNode.get());
1162 // Merging the the first paragraph of inserted content with the content that came
1163 // before the selection that was pasted into would also move content after
1164 // the selection that was pasted into if: only one paragraph was being pasted,
1165 // and it was not wrapped in a block, the selection that was pasted into ended
1166 // at the end of a block and the next paragraph didn't start at the start of a block.
1167 // Insert a line break just after the inserted content to separate it from what
1168 // comes after and prevent that from happening.
1169 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1170 if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
1171 insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
1172 // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
1173 if (!startOfParagraphToMove.deepEquivalent().inDocument())
1177 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
1178 // only ever used to create positions where inserted content starts/ends.
1179 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
1180 m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent().downstream();
1181 if (m_endOfInsertedContent.isOrphan())
1182 m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent().upstream();
1185 Position lastPositionToSelect;
1186 if (fragment.hasInterchangeNewlineAtEnd()) {
1187 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1188 VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
1190 if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
1191 if (!isStartOfParagraph(endOfInsertedContent)) {
1192 setEndingSelection(endOfInsertedContent);
1193 Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
1194 if (isListItem(enclosingNode)) {
1195 RefPtr<Node> newListItem = createListItemElement(document());
1196 insertNodeAfter(newListItem, enclosingNode);
1197 setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.get())));
1199 // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph
1200 // block's style seems to annoy users.
1201 insertParagraphSeparator(true, !startIsInsideMailBlockquote && highestEnclosingNodeOfType(endOfInsertedContent.deepEquivalent(),
1202 isMailBlockquote, CannotCrossEditingBoundary, insertedNodes.firstNodeInserted()->parentNode()));
1205 // Select up to the paragraph separator that was added.
1206 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
1207 updateNodesInserted(lastPositionToSelect.deprecatedNode());
1210 // Select up to the beginning of the next paragraph.
1211 lastPositionToSelect = next.deepEquivalent().downstream();
1217 if (Node* mailBlockquote = enclosingNodeOfType(positionAtStartOfInsertedContent().deepEquivalent(), isMailPasteAsQuotationNode))
1218 removeNodeAttribute(toElement(mailBlockquote), classAttr);
1220 if (shouldPerformSmartReplace())
1221 addSpacesForSmartReplace();
1223 // If we are dealing with a fragment created from plain text
1224 // no style matching is necessary.
1225 if (plainTextFragment)
1226 m_matchStyle = false;
1228 completeHTMLReplacement(lastPositionToSelect);
1231 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
1233 if (!endBR || !endBR->inDocument())
1236 VisiblePosition visiblePos(positionBeforeNode(endBR));
1238 // Don't remove the br if nothing was inserted.
1239 if (visiblePos.previous() == originalVisPosBeforeEndBR)
1242 // Remove the br if it is collapsed away and so is unnecessary.
1243 if (!document().inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
1246 // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
1247 // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
1248 return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
1251 bool ReplaceSelectionCommand::shouldPerformSmartReplace() const
1253 if (!m_smartReplace)
1256 Element* textControl = enclosingTextFormControl(positionAtStartOfInsertedContent().deepEquivalent());
1257 if (textControl && textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isPasswordField())
1258 return false; // Disable smart replace for password fields.
1263 static bool isCharacterSmartReplaceExemptConsideringNonBreakingSpace(UChar32 character, bool previousCharacter)
1265 return isCharacterSmartReplaceExempt(character == noBreakSpace ? ' ' : character, previousCharacter);
1268 void ReplaceSelectionCommand::addSpacesForSmartReplace()
1270 VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
1271 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1273 Position endUpstream = endOfInsertedContent.deepEquivalent().upstream();
1274 Node* endNode = endUpstream.computeNodeBeforePosition();
1275 int endOffset = endNode && endNode->isTextNode() ? toText(endNode)->length() : 0;
1276 if (endUpstream.anchorType() == Position::PositionIsOffsetInAnchor) {
1277 endNode = endUpstream.containerNode();
1278 endOffset = endUpstream.offsetInContainerNode();
1281 bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(endOfInsertedContent.characterAfter(), false);
1282 if (needsTrailingSpace && endNode) {
1283 bool collapseWhiteSpace = !endNode->renderer() || endNode->renderer()->style()->collapseWhiteSpace();
1284 if (endNode->isTextNode()) {
1285 insertTextIntoNode(toText(endNode), endOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1286 if (m_endOfInsertedContent.containerNode() == endNode)
1287 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
1289 RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1290 insertNodeAfter(node, endNode);
1291 updateNodesInserted(node.get());
1295 document().updateLayout();
1297 Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
1298 Node* startNode = startDownstream.computeNodeAfterPosition();
1299 unsigned startOffset = 0;
1300 if (startDownstream.anchorType() == Position::PositionIsOffsetInAnchor) {
1301 startNode = startDownstream.containerNode();
1302 startOffset = startDownstream.offsetInContainerNode();
1305 bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(startOfInsertedContent.previous().characterAfter(), true);
1306 if (needsLeadingSpace && startNode) {
1307 bool collapseWhiteSpace = !startNode->renderer() || startNode->renderer()->style()->collapseWhiteSpace();
1308 if (startNode->isTextNode()) {
1309 insertTextIntoNode(toText(startNode), startOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1310 if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
1311 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
1313 RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1314 // Don't updateNodesInserted. Doing so would set m_endOfInsertedContent to be the node containing the leading space,
1315 // but m_endOfInsertedContent is supposed to mark the end of pasted content.
1316 insertNodeBefore(node, startNode);
1317 m_startOfInsertedContent = firstPositionInNode(node.get());
1322 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
1324 Position start = positionAtStartOfInsertedContent().deepEquivalent();
1325 Position end = positionAtEndOfInsertedContent().deepEquivalent();
1327 // Mutation events may have deleted start or end
1328 if (start.isNotNull() && !start.isOrphan() && end.isNotNull() && !end.isOrphan()) {
1329 // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
1330 rebalanceWhitespaceAt(start);
1331 rebalanceWhitespaceAt(end);
1334 ASSERT(m_insertionStyle);
1335 applyStyle(m_insertionStyle.get(), start, end);
1338 if (lastPositionToSelect.isNotNull())
1339 end = lastPositionToSelect;
1341 mergeTextNodesAroundPosition(start, end);
1342 } else if (lastPositionToSelect.isNotNull())
1343 start = end = lastPositionToSelect;
1347 if (m_selectReplacement)
1348 setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1350 setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY, endingSelection().isDirectional()));
1353 void ReplaceSelectionCommand::mergeTextNodesAroundPosition(Position& position, Position& positionOnlyToBeUpdated)
1355 bool positionIsOffsetInAnchor = position.anchorType() == Position::PositionIsOffsetInAnchor;
1356 bool positionOnlyToBeUpdatedIsOffsetInAnchor = positionOnlyToBeUpdated.anchorType() == Position::PositionIsOffsetInAnchor;
1357 RefPtr<Text> text = 0;
1358 if (positionIsOffsetInAnchor && position.containerNode() && position.containerNode()->isTextNode())
1359 text = toText(position.containerNode());
1361 Node* before = position.computeNodeBeforePosition();
1362 if (before && before->isTextNode())
1363 text = toText(before);
1365 Node* after = position.computeNodeAfterPosition();
1366 if (after && after->isTextNode())
1367 text = toText(after);
1373 if (text->previousSibling() && text->previousSibling()->isTextNode()) {
1374 RefPtr<Text> previous = toText(text->previousSibling());
1375 insertTextIntoNode(text, 0, previous->data());
1377 if (positionIsOffsetInAnchor)
1378 position.moveToOffset(previous->length() + position.offsetInContainerNode());
1380 updatePositionForNodeRemoval(position, previous.get());
1382 if (positionOnlyToBeUpdatedIsOffsetInAnchor) {
1383 if (positionOnlyToBeUpdated.containerNode() == text)
1384 positionOnlyToBeUpdated.moveToOffset(previous->length() + positionOnlyToBeUpdated.offsetInContainerNode());
1385 else if (positionOnlyToBeUpdated.containerNode() == previous)
1386 positionOnlyToBeUpdated.moveToPosition(text, positionOnlyToBeUpdated.offsetInContainerNode());
1388 updatePositionForNodeRemoval(positionOnlyToBeUpdated, previous.get());
1390 removeNode(previous);
1392 if (text->nextSibling() && text->nextSibling()->isTextNode()) {
1393 RefPtr<Text> next = toText(text->nextSibling());
1394 unsigned originalLength = text->length();
1395 insertTextIntoNode(text, originalLength, next->data());
1397 if (!positionIsOffsetInAnchor)
1398 updatePositionForNodeRemoval(position, next.get());
1400 if (positionOnlyToBeUpdatedIsOffsetInAnchor && positionOnlyToBeUpdated.containerNode() == next)
1401 positionOnlyToBeUpdated.moveToPosition(text, originalLength + positionOnlyToBeUpdated.offsetInContainerNode());
1403 updatePositionForNodeRemoval(positionOnlyToBeUpdated, next.get());
1409 EditAction ReplaceSelectionCommand::editingAction() const
1411 return m_editAction;
1414 // If the user is inserting a list into an existing list, instead of nesting the list,
1415 // we put the list items into the existing list.
1416 Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<HTMLElement> prpListElement, Node* insertionBlock, const Position& insertPos, InsertedNodes& insertedNodes)
1418 RefPtr<HTMLElement> listElement = prpListElement;
1420 while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1)
1421 listElement = toHTMLElement(listElement->firstChild());
1423 bool isStart = isStartOfParagraph(insertPos);
1424 bool isEnd = isEndOfParagraph(insertPos);
1425 bool isMiddle = !isStart && !isEnd;
1426 Node* lastNode = insertionBlock;
1428 // If we're in the middle of a list item, we should split it into two separate
1429 // list items and insert these nodes between them.
1431 int textNodeOffset = insertPos.offsetInContainerNode();
1432 if (insertPos.deprecatedNode()->isTextNode() && textNodeOffset > 0)
1433 splitTextNode(toText(insertPos.deprecatedNode()), textNodeOffset);
1434 splitTreeToNode(insertPos.deprecatedNode(), lastNode, true);
1437 while (RefPtr<Node> listItem = listElement->firstChild()) {
1438 listElement->removeChild(listItem.get(), ASSERT_NO_EXCEPTION);
1439 if (isStart || isMiddle) {
1440 insertNodeBefore(listItem, lastNode);
1441 insertedNodes.respondToNodeInsertion(*listItem);
1443 insertNodeAfter(listItem, lastNode);
1444 insertedNodes.respondToNodeInsertion(*listItem);
1445 lastNode = listItem.get();
1447 ASSERT_NOT_REACHED();
1449 if (isStart || isMiddle)
1450 lastNode = lastNode->previousSibling();
1454 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
1459 if (m_startOfInsertedContent.isNull())
1460 m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
1462 m_endOfInsertedContent = lastPositionInOrAfterNode(&node->lastDescendant());
1465 // During simple pastes, where we're just pasting a text node into a run of text, we insert the text node
1466 // directly into the text node that holds the selection. This is much faster than the generalized code in
1467 // ReplaceSelectionCommand, and works around <https://bugs.webkit.org/show_bug.cgi?id=6148> since we don't
1468 // split text nodes.
1469 bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
1471 if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
1474 // FIXME: Would be nice to handle smart replace in the fast path.
1475 if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
1478 // e.g. when "bar" is inserted after "foo" in <div><u>foo</u></div>, "bar" should not be underlined.
1479 if (nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(endingSelection().start()))
1482 RefPtr<Node> nodeAfterInsertionPos = endingSelection().end().downstream().anchorNode();
1483 Text* textNode = toText(fragment.firstChild());
1484 // Our fragment creation code handles tabs, spaces, and newlines, so we don't have to worry about those here.
1486 Position start = endingSelection().start();
1487 Position end = replaceSelectedTextInNode(textNode->data());
1491 if (nodeAfterInsertionPos && nodeAfterInsertionPos->parentNode() && nodeAfterInsertionPos->hasTagName(brTag)
1492 && shouldRemoveEndBR(nodeAfterInsertionPos.get(), positionBeforeNode(nodeAfterInsertionPos.get())))
1493 removeNodeAndPruneAncestors(nodeAfterInsertionPos.get());
1495 VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
1497 setEndingSelection(selectionAfterReplace);
1502 } // namespace WebCore