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