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.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
30 #include "core/editing/markup.h"
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"
67 using namespace HTMLNames;
69 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID);
71 class AttributeChange {
74 : m_name(nullAtom, nullAtom, nullAtom)
78 AttributeChange(PassRefPtr<Element> element, const QualifiedName& name, const String& value)
79 : m_element(element), m_name(name), m_value(value)
85 m_element->setAttribute(m_name, AtomicString(m_value));
89 RefPtr<Element> m_element;
94 static void completeURLs(DocumentFragment& fragment, const String& baseURL)
96 Vector<AttributeChange> changes;
98 KURL parsedBaseURL(ParsedURLString, baseURL);
100 for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(*element, &fragment)) {
101 if (!element->hasAttributes())
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()));
111 size_t numChanges = changes.size();
112 for (size_t i = 0; i < numChanges; ++i)
116 class StyledMarkupAccumulator FINAL : public MarkupAccumulator {
118 enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
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();
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); }
136 enum NodeTraversalMode { EmitString, DoNotEmitString };
137 Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
139 bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; }
140 bool shouldApplyWrappingStyle(const Node& node) const
142 return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode()
143 && m_wrappingStyle && m_wrappingStyle->style();
146 Vector<String> m_reversedPrecedingMarkup;
147 const EAnnotateForInterchange m_shouldAnnotate;
148 Node* m_highestNodeToBeSerialized;
149 RefPtr<EditingStyle> m_wrappingStyle;
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)
160 void StyledMarkupAccumulator::wrapWithNode(Node& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
162 StringBuilder markup;
163 if (node.isElementNode())
164 appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode);
166 appendStartMarkup(markup, node, 0);
167 m_reversedPrecedingMarkup.append(markup.toString());
170 m_nodes->append(&node);
173 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock)
175 StringBuilder openTag;
176 appendStyleNodeOpenTag(openTag, style, document, isBlock);
177 m_reversedPrecedingMarkup.append(openTag.toString());
178 appendString(styleNodeCloseTag(isBlock));
181 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock)
183 // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
184 ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
186 out.appendLiteral("<div style=\"");
188 out.appendLiteral("<span style=\"");
189 appendAttributeValue(out, style->asText(), document.isHTMLDocument());
190 out.appendLiteral("\">");
193 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
195 DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
196 DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
197 return isBlock ? divClose : styleSpanClose;
200 String StyledMarkupAccumulator::takeResults()
202 StringBuilder result;
203 result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length());
205 for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
206 result.append(m_reversedPrecedingMarkup[i - 1]);
208 concatenateMarkup(result);
210 // We remove '\0' characters because they are not visibly rendered to the user.
211 return result.toString().replace(0, "");
214 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text)
216 const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag;
217 const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
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);
226 appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document());
229 if (!shouldAnnotate() || parentIsTextarea)
230 MarkupAccumulator::appendText(out, text);
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));
240 out.append(styleNodeCloseTag());
243 String StyledMarkupAccumulator::renderedText(Node& node, const Range* range)
245 if (!node.isTextNode())
248 const Text& textNode = toText(node);
249 unsigned startOffset = 0;
250 unsigned endOffset = textNode.length();
252 if (range && node == range->startContainer())
253 startOffset = range->startOffset();
254 if (range && node == range->endContainer())
255 endOffset = range->endOffset();
257 Position start = createLegacyEditingPosition(&node, startOffset);
258 Position end = createLegacyEditingPosition(&node, endOffset);
259 return plainText(Range::create(node.document(), start, end).get());
262 String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
265 return node.nodeValue();
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());
275 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
277 const bool documentIsHTML = element.document().isHTMLDocument();
278 appendOpenTag(out, element, 0);
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)
288 appendAttribute(out, element, attribute, 0);
291 if (shouldOverrideStyleAttr) {
292 RefPtr<EditingStyle> newInlineStyle;
294 if (shouldApplyWrappingStyle(element)) {
295 newInlineStyle = m_wrappingStyle->copy();
296 newInlineStyle->removePropertiesInElementDefaultStyle(&element);
297 newInlineStyle->removeStyleConflictingWithStyleOfNode(&element);
299 newInlineStyle = EditingStyle::create();
301 if (element.isStyledElement() && element.inlineStyle())
302 newInlineStyle->overrideWithStyle(element.inlineStyle());
304 if (shouldAnnotateOrForceInline) {
305 if (shouldAnnotate())
306 newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element));
308 if (addDisplayInline)
309 newInlineStyle->forceInline();
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);
317 if (!newInlineStyle->isEmpty()) {
318 out.appendLiteral(" style=\"");
319 appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
324 appendCloseTag(out, element);
327 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
329 if (!m_highestNodeToBeSerialized) {
330 Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString);
331 m_highestNodeToBeSerialized = lastClosed;
334 if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode())
335 m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate());
337 return traverseNodesForSerialization(startNode, pastEnd, EmitString);
340 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
342 const bool shouldEmit = traversalMode == EmitString;
343 Vector<Node*> ancestorsToClose;
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.
355 next = NodeTraversal::next(*n);
356 bool openedTag = false;
358 if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
359 // Don't write out empty block containers that aren't fully selected.
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))
368 // Add the node to the markup if we're not skipping the descendants
372 // If node has no children, close the tag now.
373 if (!n->hasChildren()) {
379 ancestorsToClose.append(n);
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();
390 if (next != pastEnd && next->isDescendantOf(ancestor))
392 // Not at the end of the range, close ancestors up to sibling of next node.
394 appendEndTag(*ancestor);
395 lastClosed = ancestor;
396 ancestorsToClose.removeLast();
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())
407 // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
408 ASSERT(startNode->isDescendantOf(parent));
410 wrapWithNode(*parent);
420 static bool isHTMLBlockElement(const Node* node)
423 return isHTMLTableCellElement(*node)
424 || isNonTableCellHTMLBlockElement(node);
427 static Node* ancestorToRetainStructureAndAppearanceForBlock(Node* commonAncestorBlock)
429 if (!commonAncestorBlock)
432 if (commonAncestorBlock->hasTagName(tbodyTag) || isHTMLTableRowElement(*commonAncestorBlock)) {
433 ContainerNode* table = commonAncestorBlock->parentNode();
434 while (table && !isHTMLTableElement(*table))
435 table = table->parentNode();
440 if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
441 return commonAncestorBlock;
446 static inline Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
448 return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor));
451 static inline Node* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor)
453 Node* commonAncestorBlock = enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement);
454 return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock);
457 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID)
461 RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
464 if (!value->isPrimitiveValue())
466 return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
469 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
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);
478 static PassRefPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const Node* node)
480 if (!node->isHTMLElement())
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();
491 static bool isElementPresentational(const Node* node)
493 return node->hasTagName(uTag) || node->hasTagName(sTag) || node->hasTagName(strikeTag)
494 || node->hasTagName(iTag) || node->hasTagName(emTag) || node->hasTagName(bTag) || node->hasTagName(strongTag);
497 static Node* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor)
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);
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();
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;
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;
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;
536 if (Node *enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag))
537 specialCommonAncestor = enclosingAnchor;
539 return specialCommonAncestor;
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)
548 ASSERT(updatedRange);
549 DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
551 bool collapsed = updatedRange->collapsed();
553 return emptyString();
554 Node* commonAncestor = updatedRange->commonAncestorContainer();
556 return emptyString();
558 document.updateLayoutIgnorePendingStylesheets();
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();
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;
576 accumulator.appendString(interchangeNewlineString);
577 startNode = visibleStart.next().deepEquivalent().deprecatedNode();
579 if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0)
580 return interchangeNewlineString;
583 Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
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);
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) + "')");
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);
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);
613 nodes->append(ancestor);
615 if (ancestor == specialCommonAncestor)
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);
624 return accumulator.takeResults();
627 String createMarkup(const Range* range, Vector<Node*>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
630 return emptyString();
632 Document& document = range->ownerDocument();
633 const Range* updatedRange = range;
635 return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
638 PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
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);
644 fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
646 if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
647 completeURLs(*fragment, baseURL);
649 return fragment.release();
652 static const char fragmentMarkerTag[] = "webkit-fragment-marker";
654 static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
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;
661 nodeAfterContext = node;
669 static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, Node* nodeAfterContext)
672 for (RefPtr<Node> node = fragment->firstChild(); node; node = next) {
673 if (nodeBeforeContext->isDescendantOf(node.get())) {
674 next = NodeTraversal::next(*node);
677 next = NodeTraversal::nextSkippingChildren(*node);
678 ASSERT(!node->contains(nodeAfterContext));
679 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
680 if (nodeBeforeContext == node)
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);
691 PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
692 const String& baseURL, ParserContentPolicy parserContentPolicy)
694 // FIXME: Need to handle the case where the markup already contains these markers.
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));
703 RefPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
704 RefPtr<Document> taggedDocument = Document::create();
705 taggedDocument->setContextFeatures(document.contextFeatures());
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);
711 RefPtr<Node> nodeBeforeContext;
712 RefPtr<Node> nodeAfterContext;
713 if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
716 RefPtrWillBeRawPtr<Range> range = Range::create(*taggedDocument.get(),
717 positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
718 positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
720 Node* commonAncestor = range->commonAncestorContainer();
721 Node* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor);
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);
730 fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
732 trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
737 String createMarkup(const Node* node, EChildrenOnly childrenOnly, Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip)
742 MarkupAccumulator accumulator(nodes, shouldResolveURLs);
743 return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip);
746 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
748 Document& document = paragraph->document();
750 if (string.isEmpty()) {
751 paragraph->appendChild(createBlockPlaceholderElement(document));
755 ASSERT(string.find('\n') == kNotFound);
757 Vector<String> tabList;
758 string.split('\t', true, tabList);
759 StringBuilder tabText;
761 size_t numEntries = tabList.size();
762 for (size_t i = 0; i < numEntries; ++i) {
763 const String& s = tabList[i];
765 // append the non-tab textual part
767 if (!tabText.isEmpty()) {
768 paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
771 RefPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
772 paragraph->appendChild(textNode.release());
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()));
786 bool isPlainTextMarkup(Node* node)
789 if (!node->isElementNode())
792 Element* element = toElement(node);
793 if (!isHTMLDivElement(*element) || !element->hasAttributes())
796 if (element->hasOneChild() && (element->firstChild()->isTextNode() || (element->firstChild()->firstChild())))
799 return element->hasChildCount(2) && isTabSpanTextNode(element->firstChild()->firstChild()) && element->lastChild()->isTextNode();
802 static bool shouldPreserveNewline(const Range& range)
804 if (Node* node = range.firstNode()) {
805 if (RenderObject* renderer = node->renderer())
806 return renderer->style()->preserveNewline();
809 if (Node* node = range.startPosition().anchorNode()) {
810 if (RenderObject* renderer = node->renderer())
811 return renderer->style()->preserveNewline();
817 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
822 Document& document = context->ownerDocument();
823 RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
826 return fragment.release();
828 String string = text;
829 string.replace("\r\n", "\n");
830 string.replace('\r', '\n');
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());
839 return fragment.release();
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();
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());
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];
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);
873 if (useClonesOfEnclosingBlock)
874 element = block->cloneElementWithoutChildren();
876 element = createDefaultParagraphElement(document);
877 fillContainerFromString(element.get(), s);
879 fragment->appendChild(element.release());
881 return fragment.release();
884 String createFullMarkup(const Node* node)
889 LocalFrame* frame = node->document().frame();
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;
902 String urlToMarkup(const KURL& url, const String& title)
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();
913 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
915 ASSERT(contextElement);
916 Document& document = isHTMLTemplateElement(*contextElement) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
917 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
919 if (document.isHTMLDocument()) {
920 fragment->parseHTML(markup, contextElement, parserContentPolicy);
924 bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
926 exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document.");
929 return fragment.release();
932 PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
934 RefPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
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));
946 bool successfulParse = fragment->parseXML(sourceString, 0);
947 if (!successfulParse)
951 // FIXME: Do we need to mess with URLs here?
953 return fragment.release();
956 static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
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);
964 fragment->removeChild(element);
967 PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
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.");
976 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
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.
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);
994 return fragment.release();
997 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
1000 RefPtr<ContainerNode> containerNode(container);
1002 ChildListMutationScope mutation(*containerNode);
1004 if (!fragment->firstChild()) {
1005 containerNode->removeChildren();
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());
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);
1021 containerNode->removeChildren();
1022 containerNode->appendChild(fragment, exceptionState);
1025 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
1028 RefPtr<ContainerNode> containerNode(container);
1030 ChildListMutationScope mutation(*containerNode);
1032 // FIXME: This is wrong if containerNode->firstChild() has more than one ref! Example:
1035 // var oldText = div.firstChild;
1036 // console.log(oldText.data); // foo
1037 // div.innerText = "bar";
1038 // console.log(oldText.data); // bar!?!
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);
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);
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);
1056 containerNode->removeChildren();
1057 containerNode->appendChild(textNode.release(), exceptionState);
1060 void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
1062 ASSERT(node && node->isTextNode());
1063 Node* next = node->nextSibling();
1064 if (!next || !next->isTextNode())
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);