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