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