Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / editing / markup.cpp
1 /*
2  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2008, 2009, 2010, 2011 Google Inc. All rights reserved.
4  * Copyright (C) 2011 Igalia S.L.
5  * Copyright (C) 2011 Motorola Mobility. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
20  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
24  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "core/editing/markup.h"
31
32 #include "bindings/core/v8/ExceptionState.h"
33 #include "core/CSSPropertyNames.h"
34 #include "core/CSSValueKeywords.h"
35 #include "core/HTMLNames.h"
36 #include "core/css/CSSPrimitiveValue.h"
37 #include "core/css/CSSValue.h"
38 #include "core/css/StylePropertySet.h"
39 #include "core/dom/CDATASection.h"
40 #include "core/dom/ChildListMutationScope.h"
41 #include "core/dom/Comment.h"
42 #include "core/dom/ContextFeatures.h"
43 #include "core/dom/DocumentFragment.h"
44 #include "core/dom/ElementTraversal.h"
45 #include "core/dom/ExceptionCode.h"
46 #include "core/dom/NodeTraversal.h"
47 #include "core/dom/Range.h"
48 #include "core/editing/Editor.h"
49 #include "core/editing/MarkupAccumulator.h"
50 #include "core/editing/TextIterator.h"
51 #include "core/editing/VisibleSelection.h"
52 #include "core/editing/VisibleUnits.h"
53 #include "core/editing/htmlediting.h"
54 #include "core/frame/LocalFrame.h"
55 #include "core/html/HTMLAnchorElement.h"
56 #include "core/html/HTMLBRElement.h"
57 #include "core/html/HTMLBodyElement.h"
58 #include "core/html/HTMLDivElement.h"
59 #include "core/html/HTMLElement.h"
60 #include "core/html/HTMLQuoteElement.h"
61 #include "core/html/HTMLSpanElement.h"
62 #include "core/html/HTMLTableCellElement.h"
63 #include "core/html/HTMLTableElement.h"
64 #include "core/html/HTMLTextFormControlElement.h"
65 #include "core/rendering/RenderObject.h"
66 #include "platform/weborigin/KURL.h"
67 #include "wtf/StdLibExtras.h"
68 #include "wtf/text/StringBuilder.h"
69
70 namespace blink {
71
72 using namespace HTMLNames;
73
74 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID);
75
76 class AttributeChange {
77     ALLOW_ONLY_INLINE_ALLOCATION();
78 public:
79     AttributeChange()
80         : m_name(nullAtom, nullAtom, nullAtom)
81     {
82     }
83
84     AttributeChange(PassRefPtrWillBeRawPtr<Element> element, const QualifiedName& name, const String& value)
85         : m_element(element), m_name(name), m_value(value)
86     {
87     }
88
89     void apply()
90     {
91         m_element->setAttribute(m_name, AtomicString(m_value));
92     }
93
94     void trace(Visitor* visitor)
95     {
96         visitor->trace(m_element);
97     }
98
99 private:
100     RefPtrWillBeMember<Element> m_element;
101     QualifiedName m_name;
102     String m_value;
103 };
104
105 } // namespace blink
106
107 WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::AttributeChange);
108
109 namespace blink {
110
111 static void completeURLs(DocumentFragment& fragment, const String& baseURL)
112 {
113     WillBeHeapVector<AttributeChange> changes;
114
115     KURL parsedBaseURL(ParsedURLString, baseURL);
116
117     for (Element& element : ElementTraversal::descendantsOf(fragment)) {
118         AttributeCollection attributes = element.attributes();
119         // AttributeCollection::iterator end = attributes.end();
120         for (const auto& attribute : attributes) {
121             if (element.isURLAttribute(attribute) && !attribute.value().isEmpty())
122                 changes.append(AttributeChange(&element, attribute.name(), KURL(parsedBaseURL, attribute.value()).string()));
123         }
124     }
125
126     for (auto& change : changes)
127         change.apply();
128 }
129
130 class StyledMarkupAccumulator final : public MarkupAccumulator {
131 public:
132     enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
133
134     StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs, EAnnotateForInterchange, RawPtr<const Range>, Node* highestNodeToBeSerialized = nullptr);
135     Node* serializeNodes(Node* startNode, Node* pastEnd);
136     void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
137     void wrapWithNode(ContainerNode&, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
138     void wrapWithStyleNode(StylePropertySet*, const Document&, bool isBlock = false);
139     String takeResults();
140
141 private:
142     void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, const Document&, bool isBlock = false);
143     const String& styleNodeCloseTag(bool isBlock = false);
144     virtual void appendText(StringBuilder& out, Text&) override;
145     String renderedText(Node&, const Range*);
146     String stringValueForRange(const Node&, const Range*);
147     void appendElement(StringBuilder& out, Element&, bool addDisplayInline, RangeFullySelectsNode);
148     virtual void appendElement(StringBuilder& out, Element& element, Namespaces*) override { appendElement(out, element, false, DoesFullySelectNode); }
149
150     enum NodeTraversalMode { EmitString, DoNotEmitString };
151     Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
152
153     bool shouldAnnotate() const { return m_shouldAnnotate == AnnotateForInterchange || m_shouldAnnotate == AnnotateForNavigationTransition; }
154     bool shouldApplyWrappingStyle(const Node& node) const
155     {
156         return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode()
157             && m_wrappingStyle && m_wrappingStyle->style();
158     }
159
160     Vector<String> m_reversedPrecedingMarkup;
161     const EAnnotateForInterchange m_shouldAnnotate;
162     RawPtrWillBeMember<Node> m_highestNodeToBeSerialized;
163     RefPtrWillBeMember<EditingStyle> m_wrappingStyle;
164 };
165
166 inline StyledMarkupAccumulator::StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate, RawPtr<const Range> range, Node* highestNodeToBeSerialized)
167     : MarkupAccumulator(nodes, shouldResolveURLs, range)
168     , m_shouldAnnotate(shouldAnnotate)
169     , m_highestNodeToBeSerialized(highestNodeToBeSerialized)
170 {
171 }
172
173 void StyledMarkupAccumulator::wrapWithNode(ContainerNode& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
174 {
175     StringBuilder markup;
176     if (node.isElementNode())
177         appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode);
178     else
179         appendStartMarkup(markup, node, 0);
180     m_reversedPrecedingMarkup.append(markup.toString());
181     if (node.isElementNode())
182         appendEndTag(toElement(node));
183     if (m_nodes)
184         m_nodes->append(&node);
185 }
186
187 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock)
188 {
189     StringBuilder openTag;
190     appendStyleNodeOpenTag(openTag, style, document, isBlock);
191     m_reversedPrecedingMarkup.append(openTag.toString());
192     appendString(styleNodeCloseTag(isBlock));
193 }
194
195 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock)
196 {
197     // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
198     ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
199     if (isBlock)
200         out.appendLiteral("<div style=\"");
201     else
202         out.appendLiteral("<span style=\"");
203     appendAttributeValue(out, style->asText(), document.isHTMLDocument());
204     out.appendLiteral("\">");
205 }
206
207 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
208 {
209     DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
210     DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
211     return isBlock ? divClose : styleSpanClose;
212 }
213
214 String StyledMarkupAccumulator::takeResults()
215 {
216     StringBuilder result;
217     result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length());
218
219     for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
220         result.append(m_reversedPrecedingMarkup[i - 1]);
221
222     concatenateMarkup(result);
223
224     // We remove '\0' characters because they are not visibly rendered to the user.
225     return result.toString().replace(0, "");
226 }
227
228 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text)
229 {
230     const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag;
231     const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
232     if (wrappingSpan) {
233         RefPtrWillBeRawPtr<EditingStyle> wrappingStyle = m_wrappingStyle->copy();
234         // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
235         // Make sure spans are inline style in paste side e.g. span { display: block }.
236         wrappingStyle->forceInline();
237         // FIXME: Should this be included in forceInline?
238         wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
239
240         appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document());
241     }
242
243     if (!shouldAnnotate() || parentIsTextarea)
244         MarkupAccumulator::appendText(out, text);
245     else {
246         const bool useRenderedText = !enclosingElementWithTag(firstPositionInNode(&text), selectTag);
247         String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range);
248         StringBuilder buffer;
249         appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA);
250         out.append(convertHTMLTextToInterchangeFormat(buffer.toString(), text));
251     }
252
253     if (wrappingSpan)
254         out.append(styleNodeCloseTag());
255 }
256
257 String StyledMarkupAccumulator::renderedText(Node& node, const Range* range)
258 {
259     if (!node.isTextNode())
260         return String();
261
262     Text& textNode = toText(node);
263     unsigned startOffset = 0;
264     unsigned endOffset = textNode.length();
265
266     if (range && textNode == range->startContainer())
267         startOffset = range->startOffset();
268     if (range && textNode == range->endContainer())
269         endOffset = range->endOffset();
270
271     Position start = createLegacyEditingPosition(&textNode, startOffset);
272     Position end = createLegacyEditingPosition(&textNode, endOffset);
273     return plainText(Range::create(textNode.document(), start, end).get());
274 }
275
276 String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
277 {
278     if (!range)
279         return node.nodeValue();
280
281     String str = node.nodeValue();
282     if (node == range->endContainer())
283         str.truncate(range->endOffset());
284     if (node == range->startContainer())
285         str.remove(0, range->startOffset());
286     return str;
287 }
288
289 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
290 {
291     const bool documentIsHTML = element.document().isHTMLDocument();
292     appendOpenTag(out, element, 0);
293
294     const bool shouldAnnotateOrForceInline = element.isHTMLElement() && (shouldAnnotate() || addDisplayInline);
295     const bool shouldOverrideStyleAttr = shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element);
296
297     AttributeCollection attributes = element.attributes();
298     for (const auto& attribute : attributes) {
299         // We'll handle the style attribute separately, below.
300         if (attribute.name() == styleAttr && shouldOverrideStyleAttr)
301             continue;
302         appendAttribute(out, element, attribute, 0);
303     }
304
305     if (shouldOverrideStyleAttr) {
306         RefPtrWillBeRawPtr<EditingStyle> newInlineStyle = nullptr;
307
308         if (shouldApplyWrappingStyle(element)) {
309             newInlineStyle = m_wrappingStyle->copy();
310             newInlineStyle->removePropertiesInElementDefaultStyle(&element);
311             newInlineStyle->removeStyleConflictingWithStyleOfElement(&element);
312         } else
313             newInlineStyle = EditingStyle::create();
314
315         if (element.isStyledElement() && element.inlineStyle())
316             newInlineStyle->overrideWithStyle(element.inlineStyle());
317
318         if (shouldAnnotateOrForceInline) {
319             if (shouldAnnotate())
320                 newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element));
321
322             if (&element == m_highestNodeToBeSerialized && m_shouldAnnotate == AnnotateForNavigationTransition)
323                 newInlineStyle->addAbsolutePositioningFromElement(element);
324
325             if (addDisplayInline)
326                 newInlineStyle->forceInline();
327
328             // If the node is not fully selected by the range, then we don't want to keep styles that affect its relationship to the nodes around it
329             // only the ones that affect it and the nodes within it.
330             if (rangeFullySelectsNode == DoesNotFullySelectNode && newInlineStyle->style())
331                 newInlineStyle->style()->removeProperty(CSSPropertyFloat);
332         }
333
334         if (!newInlineStyle->isEmpty()) {
335             out.appendLiteral(" style=\"");
336             appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
337             out.append('\"');
338         }
339     }
340
341     appendCloseTag(out, element);
342 }
343
344 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
345 {
346     if (!m_highestNodeToBeSerialized) {
347         Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString);
348         m_highestNodeToBeSerialized = lastClosed;
349     }
350
351     if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode()) {
352         m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate());
353         if (m_shouldAnnotate == AnnotateForNavigationTransition) {
354             m_wrappingStyle->style()->removeProperty(CSSPropertyBackgroundColor);
355             m_wrappingStyle->style()->removeProperty(CSSPropertyBackgroundImage);
356         }
357     }
358
359
360     return traverseNodesForSerialization(startNode, pastEnd, EmitString);
361 }
362
363 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
364 {
365     const bool shouldEmit = traversalMode == EmitString;
366     WillBeHeapVector<RawPtrWillBeMember<ContainerNode>> ancestorsToClose;
367     Node* next;
368     Node* lastClosed = nullptr;
369     for (Node* n = startNode; n != pastEnd; n = next) {
370         // According to <rdar://problem/5730668>, it is possible for n to blow
371         // past pastEnd and become null here. This shouldn't be possible.
372         // This null check will prevent crashes (but create too much markup)
373         // and the ASSERT will hopefully lead us to understanding the problem.
374         ASSERT(n);
375         if (!n)
376             break;
377
378         next = NodeTraversal::next(*n);
379         bool openedTag = false;
380
381         if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
382             // Don't write out empty block containers that aren't fully selected.
383             continue;
384
385         if (!n->renderer() && !enclosingElementWithTag(firstPositionInOrBeforeNode(n), selectTag) && m_shouldAnnotate != AnnotateForNavigationTransition) {
386             next = NodeTraversal::nextSkippingChildren(*n);
387             // Don't skip over pastEnd.
388             if (pastEnd && pastEnd->isDescendantOf(n))
389                 next = pastEnd;
390         } else {
391             // Add the node to the markup if we're not skipping the descendants
392             if (shouldEmit)
393                 appendStartTag(*n);
394
395             // If node has no children, close the tag now.
396             if (n->isContainerNode() && toContainerNode(n)->hasChildren()) {
397                 openedTag = true;
398                 ancestorsToClose.append(toContainerNode(n));
399             } else {
400                 if (shouldEmit && n->isElementNode())
401                     appendEndTag(toElement(*n));
402                 lastClosed = n;
403             }
404         }
405
406         // If we didn't insert open tag and there's no more siblings or we're at the end of the traversal, take care of ancestors.
407         // FIXME: What happens if we just inserted open tag and reached the end?
408         if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
409             // Close up the ancestors.
410             while (!ancestorsToClose.isEmpty()) {
411                 ContainerNode* ancestor = ancestorsToClose.last();
412                 ASSERT(ancestor);
413                 if (next != pastEnd && next->isDescendantOf(ancestor))
414                     break;
415                 // Not at the end of the range, close ancestors up to sibling of next node.
416                 if (shouldEmit && ancestor->isElementNode())
417                     appendEndTag(toElement(*ancestor));
418                 lastClosed = ancestor;
419                 ancestorsToClose.removeLast();
420             }
421
422             // Surround the currently accumulated markup with markup for ancestors we never opened as we leave the subtree(s) rooted at those ancestors.
423             ContainerNode* nextParent = next ? next->parentNode() : 0;
424             if (next != pastEnd && n != nextParent) {
425                 Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
426                 for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
427                     // All ancestors that aren't in the ancestorsToClose list should either be a) unrendered:
428                     if (!parent->renderer())
429                         continue;
430                     // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
431                     ASSERT(startNode->isDescendantOf(parent));
432                     if (shouldEmit)
433                         wrapWithNode(*parent);
434                     lastClosed = parent;
435                 }
436             }
437         }
438     }
439
440     return lastClosed;
441 }
442
443 static bool isHTMLBlockElement(const Node* node)
444 {
445     ASSERT(node);
446     return isHTMLTableCellElement(*node)
447         || isNonTableCellHTMLBlockElement(node);
448 }
449
450 static HTMLElement* ancestorToRetainStructureAndAppearanceForBlock(Element* commonAncestorBlock)
451 {
452     if (!commonAncestorBlock)
453         return 0;
454
455     if (commonAncestorBlock->hasTagName(tbodyTag) || isHTMLTableRowElement(*commonAncestorBlock))
456         return Traversal<HTMLTableElement>::firstAncestor(*commonAncestorBlock);
457
458     if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
459         return toHTMLElement(commonAncestorBlock);
460
461     return 0;
462 }
463
464 static inline HTMLElement* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
465 {
466     return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor));
467 }
468
469 static inline HTMLElement* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor)
470 {
471     HTMLElement* commonAncestorBlock = toHTMLElement(enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement));
472     return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock);
473 }
474
475 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID)
476 {
477     if (!style)
478         return false;
479     RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
480     if (!value)
481         return true;
482     if (!value->isPrimitiveValue())
483         return false;
484     return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
485 }
486
487 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
488 {
489     VisiblePosition next = v.next();
490     Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
491     Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
492     // Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it.
493     return isEndOfParagraph(v) && isStartOfParagraph(next) && !(isHTMLBRElement(*upstreamNode) && upstreamNode == downstreamNode);
494 }
495
496 static PassRefPtrWillBeRawPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const HTMLElement* element)
497 {
498     RefPtrWillBeRawPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle());
499     // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle
500     // the non-const-ness of styleFromMatchedRulesForElement.
501     style->mergeStyleFromRules(const_cast<HTMLElement*>(element));
502     return style.release();
503 }
504
505 static bool isPresentationalHTMLElement(const Node* node)
506 {
507     if (!node->isHTMLElement())
508         return false;
509
510     const HTMLElement& element = toHTMLElement(*node);
511     return element.hasTagName(uTag) || element.hasTagName(sTag) || element.hasTagName(strikeTag)
512         || element.hasTagName(iTag) || element.hasTagName(emTag) || element.hasTagName(bTag) || element.hasTagName(strongTag);
513 }
514
515 static HTMLElement* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor)
516 {
517     Node* commonAncestor = range->commonAncestorContainer();
518     ASSERT(commonAncestor);
519     HTMLElement* specialCommonAncestor = nullptr;
520     if (shouldAnnotate == AnnotateForInterchange) {
521         // Include ancestors that aren't completely inside the range but are required to retain
522         // the structure and appearance of the copied markup.
523         specialCommonAncestor = ancestorToRetainStructureAndAppearance(commonAncestor);
524
525         if (Node* parentListNode = enclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isListItem)) {
526             if (blink::areRangesEqual(VisibleSelection::selectionFromContentsOfNode(parentListNode).toNormalizedRange().get(), range)) {
527                 ContainerNode* ancestor = parentListNode->parentNode();
528                 while (ancestor && !isHTMLListElement(ancestor))
529                     ancestor = ancestor->parentNode();
530                 specialCommonAncestor = toHTMLElement(ancestor);
531             }
532         }
533
534         // Retain the Mail quote level by including all ancestor mail block quotes.
535         if (HTMLQuoteElement* highestMailBlockquote = toHTMLQuoteElement(highestEnclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isMailHTMLBlockquoteElement, CanCrossEditingBoundary)))
536             specialCommonAncestor = highestMailBlockquote;
537     }
538
539     Node* checkAncestor = specialCommonAncestor ? specialCommonAncestor : commonAncestor;
540     if (checkAncestor->renderer()) {
541         HTMLElement* newSpecialCommonAncestor = toHTMLElement(highestEnclosingNodeOfType(firstPositionInNode(checkAncestor), &isPresentationalHTMLElement, CanCrossEditingBoundary, constrainingAncestor));
542         if (newSpecialCommonAncestor)
543             specialCommonAncestor = newSpecialCommonAncestor;
544     }
545
546     // If a single tab is selected, commonAncestor will be a text node inside a tab span.
547     // If two or more tabs are selected, commonAncestor will be the tab span.
548     // In either case, if there is a specialCommonAncestor already, it will necessarily be above
549     // any tab span that needs to be included.
550     if (!specialCommonAncestor && isTabHTMLSpanElementTextNode(commonAncestor))
551         specialCommonAncestor = toHTMLSpanElement(commonAncestor->parentNode());
552     if (!specialCommonAncestor && isTabHTMLSpanElement(commonAncestor))
553         specialCommonAncestor = toHTMLSpanElement(commonAncestor);
554
555     if (HTMLAnchorElement* enclosingAnchor = toHTMLAnchorElement(enclosingElementWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag)))
556         specialCommonAncestor = enclosingAnchor;
557
558     return specialCommonAncestor;
559 }
560
561 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange?
562 // FIXME: At least, annotation and style info should probably not be included in range.markupString()
563 static String createMarkupInternal(Document& document, const Range* range, const Range* updatedRange, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes,
564     EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
565 {
566     ASSERT(range);
567     ASSERT(updatedRange);
568     DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
569
570     bool collapsed = updatedRange->collapsed();
571     if (collapsed)
572         return emptyString();
573     Node* commonAncestor = updatedRange->commonAncestorContainer();
574     if (!commonAncestor)
575         return emptyString();
576
577     document.updateLayoutIgnorePendingStylesheets();
578
579     HTMLBodyElement* body = toHTMLBodyElement(enclosingElementWithTag(firstPositionInNode(commonAncestor), bodyTag));
580     HTMLBodyElement* fullySelectedRoot = nullptr;
581     // FIXME: Do this for all fully selected blocks, not just the body.
582     if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range))
583         fullySelectedRoot = body;
584     HTMLElement* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange, shouldAnnotate, constrainingAncestor);
585     StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange, specialCommonAncestor);
586     Node* pastEnd = updatedRange->pastLastNode();
587
588     Node* startNode = updatedRange->firstNode();
589     VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY);
590     VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY);
591     if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) {
592         if (visibleStart == visibleEnd.previous())
593             return interchangeNewlineString;
594
595         accumulator.appendString(interchangeNewlineString);
596         startNode = visibleStart.next().deepEquivalent().deprecatedNode();
597
598         if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0)
599             return interchangeNewlineString;
600     }
601
602     Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
603
604     if (specialCommonAncestor && lastClosed) {
605         // Also include all of the ancestors of lastClosed up to this special ancestor.
606         for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) {
607             if (ancestor == fullySelectedRoot && !convertBlocksToInlines) {
608                 RefPtrWillBeRawPtr<EditingStyle> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot);
609
610                 // Bring the background attribute over, but not as an attribute because a background attribute on a div
611                 // appears to have no effect.
612                 if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue(CSSPropertyBackgroundImage))
613                     && fullySelectedRoot->hasAttribute(backgroundAttr))
614                     fullySelectedRootStyle->style()->setProperty(CSSPropertyBackgroundImage, "url('" + fullySelectedRoot->getAttribute(backgroundAttr) + "')");
615
616                 if (fullySelectedRootStyle->style()) {
617                     // Reset the CSS properties to avoid an assertion error in addStyleMarkup().
618                     // This assertion is caused at least when we select all text of a <body> element whose
619                     // 'text-decoration' property is "inherit", and copy it.
620                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration))
621                         fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone);
622                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect))
623                         fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
624                     accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true);
625                 }
626             } else {
627                 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
628                 // so that styles that affect the exterior of the node are not included.
629                 accumulator.wrapWithNode(*ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
630             }
631             if (nodes)
632                 nodes->append(ancestor);
633
634             if (ancestor == specialCommonAncestor)
635                 break;
636         }
637     }
638
639     // FIXME: The interchange newline should be placed in the block that it's in, not after all of the content, unconditionally.
640     if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous()))
641         accumulator.appendString(interchangeNewlineString);
642
643     return accumulator.takeResults();
644 }
645
646 String createMarkup(const Range* range, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
647 {
648     if (!range)
649         return emptyString();
650
651     Document& document = range->ownerDocument();
652     const Range* updatedRange = range;
653
654     return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
655 }
656
657 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
658 {
659     // We use a fake body element here to trick the HTML parser to using the InBody insertion mode.
660     RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document);
661     RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
662
663     fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
664
665     if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
666         completeURLs(*fragment, baseURL);
667
668     return fragment.release();
669 }
670
671 static const char fragmentMarkerTag[] = "webkit-fragment-marker";
672
673 static bool findNodesSurroundingContext(Document* document, RefPtrWillBeRawPtr<Comment>& nodeBeforeContext, RefPtrWillBeRawPtr<Comment>& nodeAfterContext)
674 {
675     for (Node& node : NodeTraversal::startsAt(document->firstChild())) {
676         if (node.nodeType() == Node::COMMENT_NODE && toComment(node).data() == fragmentMarkerTag) {
677             if (!nodeBeforeContext)
678                 nodeBeforeContext = &toComment(node);
679             else {
680                 nodeAfterContext = &toComment(node);
681                 return true;
682             }
683         }
684     }
685     return false;
686 }
687
688 static void trimFragment(DocumentFragment* fragment, Comment* nodeBeforeContext, Comment* nodeAfterContext)
689 {
690     RefPtrWillBeRawPtr<Node> next = nullptr;
691     for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = next) {
692         if (nodeBeforeContext->isDescendantOf(node.get())) {
693             next = NodeTraversal::next(*node);
694             continue;
695         }
696         next = NodeTraversal::nextSkippingChildren(*node);
697         ASSERT(!node->contains(nodeAfterContext));
698         node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
699         if (nodeBeforeContext == node)
700             break;
701     }
702
703     ASSERT(nodeAfterContext->parentNode());
704     for (RefPtrWillBeRawPtr<Node> node = nodeAfterContext; node; node = next) {
705         next = NodeTraversal::nextSkippingChildren(*node);
706         node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
707     }
708 }
709
710 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
711     const String& baseURL, ParserContentPolicy parserContentPolicy)
712 {
713     // FIXME: Need to handle the case where the markup already contains these markers.
714
715     StringBuilder taggedMarkup;
716     taggedMarkup.append(markup.left(fragmentStart));
717     MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
718     taggedMarkup.append(markup.substring(fragmentStart, fragmentEnd - fragmentStart));
719     MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
720     taggedMarkup.append(markup.substring(fragmentEnd));
721
722     RefPtrWillBeRawPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
723     RefPtrWillBeRawPtr<Document> taggedDocument = Document::create();
724     taggedDocument->setContextFeatures(document.contextFeatures());
725
726     // FIXME: It's not clear what this code is trying to do. It puts nodes as direct children of a
727     // Document that are not normally allowed by using the parser machinery.
728     taggedDocument->parserTakeAllChildrenFrom(*taggedFragment);
729
730     RefPtrWillBeRawPtr<Comment> nodeBeforeContext = nullptr;
731     RefPtrWillBeRawPtr<Comment> nodeAfterContext = nullptr;
732     if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
733         return nullptr;
734
735     RefPtrWillBeRawPtr<Range> range = Range::create(*taggedDocument.get(),
736         positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
737         positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
738
739     Node* commonAncestor = range->commonAncestorContainer();
740     HTMLElement* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor);
741
742     // When there's a special common ancestor outside of the fragment, we must include it as well to
743     // preserve the structure and appearance of the fragment. For example, if the fragment contains
744     // TD, we need to include the enclosing TABLE tag as well.
745     RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
746     if (specialCommonAncestor)
747         fragment->appendChild(specialCommonAncestor);
748     else
749         fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
750
751     trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
752
753     return fragment;
754 }
755
756 String createMarkup(const Node* node, EChildrenOnly childrenOnly, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip)
757 {
758     if (!node)
759         return "";
760
761     MarkupAccumulator accumulator(nodes, shouldResolveURLs);
762     return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip);
763 }
764
765 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
766 {
767     Document& document = paragraph->document();
768
769     if (string.isEmpty()) {
770         paragraph->appendChild(createBlockPlaceholderElement(document));
771         return;
772     }
773
774     ASSERT(string.find('\n') == kNotFound);
775
776     Vector<String> tabList;
777     string.split('\t', true, tabList);
778     StringBuilder tabText;
779     bool first = true;
780     size_t numEntries = tabList.size();
781     for (size_t i = 0; i < numEntries; ++i) {
782         const String& s = tabList[i];
783
784         // append the non-tab textual part
785         if (!s.isEmpty()) {
786             if (!tabText.isEmpty()) {
787                 paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
788                 tabText.clear();
789             }
790             RefPtrWillBeRawPtr<Text> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
791             paragraph->appendChild(textNode.release());
792         }
793
794         // there is a tab after every entry, except the last entry
795         // (if the last character is a tab, the list gets an extra empty entry)
796         if (i + 1 != numEntries)
797             tabText.append('\t');
798         else if (!tabText.isEmpty())
799             paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
800
801         first = false;
802     }
803 }
804
805 bool isPlainTextMarkup(Node* node)
806 {
807     ASSERT(node);
808     if (!isHTMLDivElement(*node))
809         return false;
810
811     HTMLDivElement& element = toHTMLDivElement(*node);
812     if (!element.hasAttributes())
813         return false;
814
815     if (element.hasOneChild())
816         return element.firstChild()->isTextNode() || element.firstChild()->hasChildren();
817
818     return element.hasChildCount(2) && isTabHTMLSpanElementTextNode(element.firstChild()->firstChild()) && element.lastChild()->isTextNode();
819 }
820
821 static bool shouldPreserveNewline(const Range& range)
822 {
823     if (Node* node = range.firstNode()) {
824         if (RenderObject* renderer = node->renderer())
825             return renderer->style()->preserveNewline();
826     }
827
828     if (Node* node = range.startPosition().anchorNode()) {
829         if (RenderObject* renderer = node->renderer())
830             return renderer->style()->preserveNewline();
831     }
832
833     return false;
834 }
835
836 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
837 {
838     if (!context)
839         return nullptr;
840
841     Document& document = context->ownerDocument();
842     RefPtrWillBeRawPtr<DocumentFragment> fragment = document.createDocumentFragment();
843
844     if (text.isEmpty())
845         return fragment.release();
846
847     String string = text;
848     string.replace("\r\n", "\n");
849     string.replace('\r', '\n');
850
851     if (shouldPreserveNewline(*context)) {
852         fragment->appendChild(document.createTextNode(string));
853         if (string.endsWith('\n')) {
854             RefPtrWillBeRawPtr<HTMLBRElement> element = createBreakElement(document);
855             element->setAttribute(classAttr, AppleInterchangeNewline);
856             fragment->appendChild(element.release());
857         }
858         return fragment.release();
859     }
860
861     // A string with no newlines gets added inline, rather than being put into a paragraph.
862     if (string.find('\n') == kNotFound) {
863         fillContainerFromString(fragment.get(), string);
864         return fragment.release();
865     }
866
867     // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
868     Element* block = enclosingBlock(context->firstNode());
869     bool useClonesOfEnclosingBlock = block
870         && !isHTMLBodyElement(*block)
871         && !isHTMLHtmlElement(*block)
872         && block != editableRootForPosition(context->startPosition());
873     bool useLineBreak = enclosingTextFormControl(context->startPosition());
874
875     Vector<String> list;
876     string.split('\n', true, list); // true gets us empty strings in the list
877     size_t numLines = list.size();
878     for (size_t i = 0; i < numLines; ++i) {
879         const String& s = list[i];
880
881         RefPtrWillBeRawPtr<Element> element = nullptr;
882         if (s.isEmpty() && i + 1 == numLines) {
883             // For last line, use the "magic BR" rather than a P.
884             element = createBreakElement(document);
885             element->setAttribute(classAttr, AppleInterchangeNewline);
886         } else if (useLineBreak) {
887             element = createBreakElement(document);
888             fillContainerFromString(fragment.get(), s);
889         } else {
890             if (useClonesOfEnclosingBlock)
891                 element = block->cloneElementWithoutChildren();
892             else
893                 element = createDefaultParagraphElement(document);
894             fillContainerFromString(element.get(), s);
895         }
896         fragment->appendChild(element.release());
897     }
898     return fragment.release();
899 }
900
901 String urlToMarkup(const KURL& url, const String& title)
902 {
903     StringBuilder markup;
904     markup.appendLiteral("<a href=\"");
905     markup.append(url.string());
906     markup.appendLiteral("\">");
907     MarkupAccumulator::appendCharactersReplacingEntities(markup, title, 0, title.length(), EntityMaskInPCDATA);
908     markup.appendLiteral("</a>");
909     return markup.toString();
910 }
911
912 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
913 {
914     ASSERT(contextElement);
915     Document& document = isHTMLTemplateElement(*contextElement) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
916     RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
917
918     if (document.isHTMLDocument()) {
919         fragment->parseHTML(markup, contextElement, parserContentPolicy);
920         return fragment;
921     }
922
923     bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
924     if (!wasValid) {
925         exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document.");
926         return nullptr;
927     }
928     return fragment.release();
929 }
930
931 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
932 {
933     RefPtrWillBeRawPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
934
935     if (sourceMIMEType == "text/html") {
936         // As far as I can tell, there isn't a spec for how transformToFragment is supposed to work.
937         // Based on the documentation I can find, it looks like we want to start parsing the fragment in the InBody insertion mode.
938         // Unfortunately, that's an implementation detail of the parser.
939         // We achieve that effect here by passing in a fake body element as context for the fragment.
940         RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
941         fragment->parseHTML(sourceString, fakeBody.get());
942     } else if (sourceMIMEType == "text/plain") {
943         fragment->parserAppendChild(Text::create(outputDoc, sourceString));
944     } else {
945         bool successfulParse = fragment->parseXML(sourceString, 0);
946         if (!successfulParse)
947             return nullptr;
948     }
949
950     // FIXME: Do we need to mess with URLs here?
951
952     return fragment.release();
953 }
954
955 static inline void removeElementPreservingChildren(PassRefPtrWillBeRawPtr<DocumentFragment> fragment, HTMLElement* element)
956 {
957     RefPtrWillBeRawPtr<Node> nextChild = nullptr;
958     for (RefPtrWillBeRawPtr<Node> child = element->firstChild(); child; child = nextChild) {
959         nextChild = child->nextSibling();
960         element->removeChild(child.get());
961         fragment->insertBefore(child, element);
962     }
963     fragment->removeChild(element);
964 }
965
966 static inline bool isSupportedContainer(Element* element)
967 {
968     ASSERT(element);
969     if (!element->isHTMLElement())
970         return true;
971
972     HTMLElement& htmlElement = toHTMLElement(*element);
973     if (htmlElement.hasTagName(colTag) || htmlElement.hasTagName(colgroupTag) || htmlElement.hasTagName(framesetTag)
974         || htmlElement.hasTagName(headTag) || htmlElement.hasTagName(styleTag) || htmlElement.hasTagName(titleTag)) {
975         return false;
976     }
977     return !htmlElement.ieForbidsInsertHTML();
978 }
979
980 PassRefPtrWillBeRawPtr<DocumentFragment> createContextualFragment(const String& markup, Element* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
981 {
982     ASSERT(element);
983     if (!isSupportedContainer(element)) {
984         exceptionState.throwDOMException(NotSupportedError, "The range's container is '" + element->localName() + "', which is not supported.");
985         return nullptr;
986     }
987
988     RefPtrWillBeRawPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
989     if (!fragment)
990         return nullptr;
991
992     // We need to pop <html> and <body> elements and remove <head> to
993     // accommodate folks passing complete HTML documents to make the
994     // child of an element.
995
996     RefPtrWillBeRawPtr<Node> nextNode = nullptr;
997     for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
998         nextNode = node->nextSibling();
999         if (isHTMLHtmlElement(*node) || isHTMLHeadElement(*node) || isHTMLBodyElement(*node)) {
1000             HTMLElement* element = toHTMLElement(node);
1001             if (Node* firstChild = element->firstChild())
1002                 nextNode = firstChild;
1003             removeElementPreservingChildren(fragment, element);
1004         }
1005     }
1006     return fragment.release();
1007 }
1008
1009 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtrWillBeRawPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
1010 {
1011     ASSERT(container);
1012     RefPtrWillBeRawPtr<ContainerNode> containerNode(container);
1013
1014     ChildListMutationScope mutation(*containerNode);
1015
1016     if (!fragment->firstChild()) {
1017         containerNode->removeChildren();
1018         return;
1019     }
1020
1021     // FIXME: This is wrong if containerNode->firstChild() has more than one ref!
1022     if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) {
1023         toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data());
1024         return;
1025     }
1026
1027     // FIXME: No need to replace the child it is a text node and its contents are already == text.
1028     if (containerNode->hasOneChild()) {
1029         containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState);
1030         return;
1031     }
1032
1033     containerNode->removeChildren();
1034     containerNode->appendChild(fragment, exceptionState);
1035 }
1036
1037 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
1038 {
1039     ASSERT(container);
1040     RefPtrWillBeRawPtr<ContainerNode> containerNode(container);
1041
1042     ChildListMutationScope mutation(*containerNode);
1043
1044     // FIXME: This is wrong if containerNode->firstChild() has more than one ref! Example:
1045     // <div>foo</div>
1046     // <script>
1047     // var oldText = div.firstChild;
1048     // console.log(oldText.data); // foo
1049     // div.innerText = "bar";
1050     // console.log(oldText.data); // bar!?!
1051     // </script>
1052     // I believe this is an intentional benchmark cheat from years ago.
1053     // We should re-visit if we actually want this still.
1054     if (containerNode->hasOneTextChild()) {
1055         toText(containerNode->firstChild())->setData(text);
1056         return;
1057     }
1058
1059     // NOTE: This method currently always creates a text node, even if that text node will be empty.
1060     RefPtrWillBeRawPtr<Text> textNode = Text::create(containerNode->document(), text);
1061
1062     // FIXME: No need to replace the child it is a text node and its contents are already == text.
1063     if (containerNode->hasOneChild()) {
1064         containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState);
1065         return;
1066     }
1067
1068     containerNode->removeChildren();
1069     containerNode->appendChild(textNode.release(), exceptionState);
1070 }
1071
1072 void mergeWithNextTextNode(Text* textNode, ExceptionState& exceptionState)
1073 {
1074     ASSERT(textNode);
1075     Node* next = textNode->nextSibling();
1076     if (!next || !next->isTextNode())
1077         return;
1078
1079     RefPtrWillBeRawPtr<Text> textNext = toText(next);
1080     textNode->appendData(textNext->data());
1081     if (textNext->parentNode()) // Might have been removed by mutation event.
1082         textNext->remove(exceptionState);
1083 }
1084
1085 String createStyledMarkupForNavigationTransition(Node* node)
1086 {
1087     node->document().updateLayoutIgnorePendingStylesheets();
1088
1089     StyledMarkupAccumulator accumulator(0, ResolveAllURLs, AnnotateForNavigationTransition, nullptr, 0);
1090     accumulator.serializeNodes(node, NodeTraversal::nextSkippingChildren(*node));
1091
1092     static const char* documentMarkup = "<!DOCTYPE html><meta name=\"viewport\" content=\"width=device-width, user-scalable=0\">";
1093     return documentMarkup + accumulator.takeResults();
1094 }
1095
1096 }