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/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"
66 using namespace HTMLNames;
68 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID);
70 class AttributeChange {
73 : m_name(nullAtom, nullAtom, nullAtom)
77 AttributeChange(PassRefPtr<Element> element, const QualifiedName& name, const String& value)
78 : m_element(element), m_name(name), m_value(value)
84 m_element->setAttribute(m_name, AtomicString(m_value));
88 RefPtr<Element> m_element;
93 static void completeURLs(DocumentFragment& fragment, const String& baseURL)
95 Vector<AttributeChange> changes;
97 KURL parsedBaseURL(ParsedURLString, baseURL);
99 for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(*element, &fragment)) {
100 if (!element->hasAttributes())
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()));
110 size_t numChanges = changes.size();
111 for (size_t i = 0; i < numChanges; ++i)
115 class StyledMarkupAccumulator FINAL : public MarkupAccumulator {
117 enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
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();
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); }
135 enum NodeTraversalMode { EmitString, DoNotEmitString };
136 Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
138 bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; }
139 bool shouldApplyWrappingStyle(const Node& node) const
141 return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode()
142 && m_wrappingStyle && m_wrappingStyle->style();
145 Vector<String> m_reversedPrecedingMarkup;
146 const EAnnotateForInterchange m_shouldAnnotate;
147 Node* m_highestNodeToBeSerialized;
148 RefPtr<EditingStyle> m_wrappingStyle;
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)
159 void StyledMarkupAccumulator::wrapWithNode(Node& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
161 StringBuilder markup;
162 if (node.isElementNode())
163 appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode);
165 appendStartMarkup(markup, node, 0);
166 m_reversedPrecedingMarkup.append(markup.toString());
169 m_nodes->append(&node);
172 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock)
174 StringBuilder openTag;
175 appendStyleNodeOpenTag(openTag, style, document, isBlock);
176 m_reversedPrecedingMarkup.append(openTag.toString());
177 appendString(styleNodeCloseTag(isBlock));
180 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock)
182 // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
183 ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
185 out.appendLiteral("<div style=\"");
187 out.appendLiteral("<span style=\"");
188 appendAttributeValue(out, style->asText(), document.isHTMLDocument());
189 out.appendLiteral("\">");
192 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
194 DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
195 DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
196 return isBlock ? divClose : styleSpanClose;
199 String StyledMarkupAccumulator::takeResults()
201 StringBuilder result;
202 result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length());
204 for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
205 result.append(m_reversedPrecedingMarkup[i - 1]);
207 concatenateMarkup(result);
209 // We remove '\0' characters because they are not visibly rendered to the user.
210 return result.toString().replace(0, "");
213 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text)
215 const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag;
216 const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
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);
225 appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document());
228 if (!shouldAnnotate() || parentIsTextarea)
229 MarkupAccumulator::appendText(out, text);
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));
239 out.append(styleNodeCloseTag());
242 String StyledMarkupAccumulator::renderedText(Node& node, const Range* range)
244 if (!node.isTextNode())
247 const Text& textNode = toText(node);
248 unsigned startOffset = 0;
249 unsigned endOffset = textNode.length();
251 if (range && node == range->startContainer())
252 startOffset = range->startOffset();
253 if (range && node == range->endContainer())
254 endOffset = range->endOffset();
256 Position start = createLegacyEditingPosition(&node, startOffset);
257 Position end = createLegacyEditingPosition(&node, endOffset);
258 return plainText(Range::create(node.document(), start, end).get());
261 String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
264 return node.nodeValue();
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());
274 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
276 const bool documentIsHTML = element.document().isHTMLDocument();
277 appendOpenTag(out, element, 0);
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)
287 appendAttribute(out, element, *attribute, 0);
290 if (shouldOverrideStyleAttr) {
291 RefPtr<EditingStyle> newInlineStyle;
293 if (shouldApplyWrappingStyle(element)) {
294 newInlineStyle = m_wrappingStyle->copy();
295 newInlineStyle->removePropertiesInElementDefaultStyle(&element);
296 newInlineStyle->removeStyleConflictingWithStyleOfNode(&element);
298 newInlineStyle = EditingStyle::create();
300 if (element.isStyledElement() && element.inlineStyle())
301 newInlineStyle->overrideWithStyle(element.inlineStyle());
303 if (shouldAnnotateOrForceInline) {
304 if (shouldAnnotate())
305 newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element));
307 if (addDisplayInline)
308 newInlineStyle->forceInline();
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);
316 if (!newInlineStyle->isEmpty()) {
317 out.appendLiteral(" style=\"");
318 appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
323 appendCloseTag(out, element);
326 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
328 if (!m_highestNodeToBeSerialized) {
329 Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString);
330 m_highestNodeToBeSerialized = lastClosed;
333 if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode())
334 m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate());
336 return traverseNodesForSerialization(startNode, pastEnd, EmitString);
339 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
341 const bool shouldEmit = traversalMode == EmitString;
342 Vector<Node*> ancestorsToClose;
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.
354 next = NodeTraversal::next(*n);
355 bool openedTag = false;
357 if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
358 // Don't write out empty block containers that aren't fully selected.
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))
367 // Add the node to the markup if we're not skipping the descendants
371 // If node has no children, close the tag now.
372 if (!n->childNodeCount()) {
378 ancestorsToClose.append(n);
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();
389 if (next != pastEnd && next->isDescendantOf(ancestor))
391 // Not at the end of the range, close ancestors up to sibling of next node.
393 appendEndTag(*ancestor);
394 lastClosed = ancestor;
395 ancestorsToClose.removeLast();
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())
406 // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
407 ASSERT(startNode->isDescendantOf(parent));
409 wrapWithNode(*parent);
419 static bool isHTMLBlockElement(const Node* node)
421 return node->hasTagName(tdTag)
422 || node->hasTagName(thTag)
423 || isNonTableCellHTMLBlockElement(node);
426 static Node* ancestorToRetainStructureAndAppearanceForBlock(Node* commonAncestorBlock)
428 if (!commonAncestorBlock)
431 if (commonAncestorBlock->hasTagName(tbodyTag) || commonAncestorBlock->hasTagName(trTag)) {
432 ContainerNode* table = commonAncestorBlock->parentNode();
433 while (table && !table->hasTagName(tableTag))
434 table = table->parentNode();
439 if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
440 return commonAncestorBlock;
445 static inline Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
447 return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor));
450 static inline Node* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor)
452 Node* commonAncestorBlock = enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement);
453 return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock);
456 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID)
460 RefPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
463 if (!value->isPrimitiveValue())
465 return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
468 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
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);
477 static PassRefPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const Node* node)
479 if (!node->isHTMLElement())
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();
490 static bool isElementPresentational(const Node* node)
492 return node->hasTagName(uTag) || node->hasTagName(sTag) || node->hasTagName(strikeTag)
493 || node->hasTagName(iTag) || node->hasTagName(emTag) || node->hasTagName(bTag) || node->hasTagName(strongTag);
496 static Node* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor)
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);
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();
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;
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;
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;
535 if (Node *enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag))
536 specialCommonAncestor = enclosingAnchor;
538 return specialCommonAncestor;
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)
547 ASSERT(updatedRange);
548 DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
550 bool collapsed = updatedRange->collapsed(ASSERT_NO_EXCEPTION);
552 return emptyString();
553 Node* commonAncestor = updatedRange->commonAncestorContainer(ASSERT_NO_EXCEPTION);
555 return emptyString();
557 document.updateLayoutIgnorePendingStylesheets();
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();
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;
575 accumulator.appendString(interchangeNewlineString);
576 startNode = visibleStart.next().deepEquivalent().deprecatedNode();
578 if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0)
579 return interchangeNewlineString;
582 Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
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);
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) + "')");
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);
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);
612 nodes->append(ancestor);
614 if (ancestor == specialCommonAncestor)
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);
623 return accumulator.takeResults();
626 String createMarkup(const Range* range, Vector<Node*>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
629 return emptyString();
631 Document& document = range->ownerDocument();
632 const Range* updatedRange = range;
634 return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
637 PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
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);
643 fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
645 if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
646 completeURLs(*fragment, baseURL);
648 return fragment.release();
651 static const char fragmentMarkerTag[] = "webkit-fragment-marker";
653 static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
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;
660 nodeAfterContext = node;
668 static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, Node* nodeAfterContext)
671 for (RefPtr<Node> node = fragment->firstChild(); node; node = next) {
672 if (nodeBeforeContext->isDescendantOf(node.get())) {
673 next = NodeTraversal::next(*node);
676 next = NodeTraversal::nextSkippingChildren(*node);
677 ASSERT(!node->contains(nodeAfterContext));
678 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
679 if (nodeBeforeContext == node)
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);
690 PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
691 const String& baseURL, ParserContentPolicy parserContentPolicy)
693 // FIXME: Need to handle the case where the markup already contains these markers.
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));
702 RefPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
703 RefPtr<Document> taggedDocument = Document::create();
704 taggedDocument->setContextFeatures(document.contextFeatures());
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);
710 RefPtr<Node> nodeBeforeContext;
711 RefPtr<Node> nodeAfterContext;
712 if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
715 RefPtr<Range> range = Range::create(*taggedDocument.get(),
716 positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
717 positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
719 Node* commonAncestor = range->commonAncestorContainer(ASSERT_NO_EXCEPTION);
720 Node* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor);
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);
729 fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
731 trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
736 String createMarkup(const Node* node, EChildrenOnly childrenOnly, Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip)
741 MarkupAccumulator accumulator(nodes, shouldResolveURLs);
742 return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip);
745 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
747 Document& document = paragraph->document();
749 if (string.isEmpty()) {
750 paragraph->appendChild(createBlockPlaceholderElement(document));
754 ASSERT(string.find('\n') == kNotFound);
756 Vector<String> tabList;
757 string.split('\t', true, tabList);
758 StringBuilder tabText;
760 size_t numEntries = tabList.size();
761 for (size_t i = 0; i < numEntries; ++i) {
762 const String& s = tabList[i];
764 // append the non-tab textual part
766 if (!tabText.isEmpty()) {
767 paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
770 RefPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
771 paragraph->appendChild(textNode.release());
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()));
785 bool isPlainTextMarkup(Node *node)
787 if (!node->isElementNode() || !node->hasTagName(divTag) || toElement(node)->hasAttributes())
790 if (node->childNodeCount() == 1 && (node->firstChild()->isTextNode() || (node->firstChild()->firstChild())))
793 return (node->childNodeCount() == 2 && isTabSpanTextNode(node->firstChild()->firstChild()) && node->firstChild()->nextSibling()->isTextNode());
796 static bool shouldPreserveNewline(const Range& range)
798 if (Node* node = range.firstNode()) {
799 if (RenderObject* renderer = node->renderer())
800 return renderer->style()->preserveNewline();
803 if (Node* node = range.startPosition().anchorNode()) {
804 if (RenderObject* renderer = node->renderer())
805 return renderer->style()->preserveNewline();
811 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
816 Document& document = context->ownerDocument();
817 RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
820 return fragment.release();
822 String string = text;
823 string.replace("\r\n", "\n");
824 string.replace('\r', '\n');
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());
833 return fragment.release();
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();
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());
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];
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);
867 if (useClonesOfEnclosingBlock)
868 element = block->cloneElementWithoutChildren();
870 element = createDefaultParagraphElement(document);
871 fillContainerFromString(element.get(), s);
873 fragment->appendChild(element.release());
875 return fragment.release();
878 String createFullMarkup(const Node* node)
883 Frame* frame = node->document().frame();
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;
896 String urlToMarkup(const KURL& url, const String& title)
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();
907 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
909 Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
910 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
912 if (document.isHTMLDocument()) {
913 fragment->parseHTML(markup, contextElement, parserContentPolicy);
917 bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
919 exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document.");
922 return fragment.release();
925 PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
927 RefPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
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));
939 bool successfulParse = fragment->parseXML(sourceString, 0);
940 if (!successfulParse)
944 // FIXME: Do we need to mess with URLs here?
946 return fragment.release();
949 static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
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);
957 fragment->removeChild(element);
960 PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
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.");
969 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
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.
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);
987 return fragment.release();
990 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
993 RefPtr<ContainerNode> containerNode(container);
995 ChildListMutationScope mutation(*containerNode);
997 if (!fragment->firstChild()) {
998 containerNode->removeChildren();
1002 if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) {
1003 toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data());
1007 if (containerNode->hasOneChild()) {
1008 containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState);
1012 containerNode->removeChildren();
1013 containerNode->appendChild(fragment, exceptionState);
1016 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
1019 RefPtr<ContainerNode> containerNode(container);
1021 ChildListMutationScope mutation(*containerNode);
1023 if (containerNode->hasOneTextChild()) {
1024 toText(containerNode->firstChild())->setData(text);
1028 RefPtr<Text> textNode = Text::create(containerNode->document(), text);
1030 if (containerNode->hasOneChild()) {
1031 containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState);
1035 containerNode->removeChildren();
1036 containerNode->appendChild(textNode.release(), exceptionState);
1039 void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
1041 ASSERT(node && node->isTextNode());
1042 Node* next = node->nextSibling();
1043 if (!next || !next->isTextNode())
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);