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/ExceptionMessages.h"
36 #include "bindings/v8/ExceptionState.h"
37 #include "core/css/CSSPrimitiveValue.h"
38 #include "core/css/CSSValue.h"
39 #include "core/css/StylePropertySet.h"
40 #include "core/dom/CDATASection.h"
41 #include "core/dom/ChildListMutationScope.h"
42 #include "core/dom/ContextFeatures.h"
43 #include "core/dom/DocumentFragment.h"
44 #include "core/dom/ElementTraversal.h"
45 #include "core/dom/ExceptionCode.h"
46 #include "core/dom/NodeTraversal.h"
47 #include "core/dom/Range.h"
48 #include "core/editing/Editor.h"
49 #include "core/editing/MarkupAccumulator.h"
50 #include "core/editing/TextIterator.h"
51 #include "core/editing/VisibleSelection.h"
52 #include "core/editing/VisibleUnits.h"
53 #include "core/editing/htmlediting.h"
54 #include "core/html/HTMLBodyElement.h"
55 #include "core/html/HTMLElement.h"
56 #include "core/html/HTMLHtmlElement.h"
57 #include "core/html/HTMLTableElement.h"
58 #include "core/html/HTMLTextFormControlElement.h"
59 #include "core/frame/Frame.h"
60 #include "core/rendering/RenderObject.h"
61 #include "weborigin/KURL.h"
62 #include "wtf/StdLibExtras.h"
63 #include "wtf/text/StringBuilder.h"
69 using namespace HTMLNames;
71 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID);
73 class AttributeChange {
76 : m_name(nullAtom, nullAtom, nullAtom)
80 AttributeChange(PassRefPtr<Element> element, const QualifiedName& name, const String& value)
81 : m_element(element), m_name(name), m_value(value)
87 m_element->setAttribute(m_name, m_value);
91 RefPtr<Element> m_element;
96 static void completeURLs(DocumentFragment* fragment, const String& baseURL)
98 Vector<AttributeChange> changes;
100 KURL parsedBaseURL(ParsedURLString, baseURL);
102 for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(element, fragment)) {
103 if (!element->hasAttributes())
105 unsigned length = element->attributeCount();
106 for (unsigned i = 0; i < length; i++) {
107 const Attribute* attribute = element->attributeItem(i);
108 if (element->isURLAttribute(*attribute) && !attribute->value().isEmpty())
109 changes.append(AttributeChange(element, attribute->name(), KURL(parsedBaseURL, attribute->value()).string()));
113 size_t numChanges = changes.size();
114 for (size_t i = 0; i < numChanges; ++i)
118 class StyledMarkupAccumulator : public MarkupAccumulator {
120 enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
122 StyledMarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs, EAnnotateForInterchange, const Range*, Node* highestNodeToBeSerialized = 0);
123 Node* serializeNodes(Node* startNode, Node* pastEnd);
124 virtual void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
125 void wrapWithNode(Node*, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
126 void wrapWithStyleNode(StylePropertySet*, Document*, bool isBlock = false);
127 String takeResults();
130 void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, Document*, bool isBlock = false);
131 const String& styleNodeCloseTag(bool isBlock = false);
132 virtual void appendText(StringBuilder& out, Text*);
133 String renderedText(const Node*, const Range*);
134 String stringValueForRange(const Node*, const Range*);
135 void appendElement(StringBuilder& out, Element*, bool addDisplayInline, RangeFullySelectsNode);
136 void appendElement(StringBuilder& out, Element* element, Namespaces*) { appendElement(out, element, false, DoesFullySelectNode); }
138 enum NodeTraversalMode { EmitString, DoNotEmitString };
139 Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
141 bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; }
142 bool shouldApplyWrappingStyle(Node* node) const
144 return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node->parentNode()
145 && m_wrappingStyle && m_wrappingStyle->style();
148 Vector<String> m_reversedPrecedingMarkup;
149 const EAnnotateForInterchange m_shouldAnnotate;
150 Node* m_highestNodeToBeSerialized;
151 RefPtr<EditingStyle> m_wrappingStyle;
154 inline StyledMarkupAccumulator::StyledMarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate,
155 const Range* range, Node* highestNodeToBeSerialized)
156 : MarkupAccumulator(nodes, shouldResolveURLs, range)
157 , m_shouldAnnotate(shouldAnnotate)
158 , m_highestNodeToBeSerialized(highestNodeToBeSerialized)
162 void StyledMarkupAccumulator::wrapWithNode(Node* node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
164 StringBuilder markup;
165 if (node->isElementNode())
166 appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(const_cast<Node*>(node)), rangeFullySelectsNode);
168 appendStartMarkup(markup, node, 0);
169 m_reversedPrecedingMarkup.append(markup.toString());
172 m_nodes->append(node);
175 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, Document* document, bool isBlock)
177 StringBuilder openTag;
178 appendStyleNodeOpenTag(openTag, style, document, isBlock);
179 m_reversedPrecedingMarkup.append(openTag.toString());
180 appendString(styleNodeCloseTag(isBlock));
183 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, Document* document, bool isBlock)
185 // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
186 ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
188 out.appendLiteral("<div style=\"");
190 out.appendLiteral("<span style=\"");
191 appendAttributeValue(out, style->asText(), document->isHTMLDocument());
196 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
198 DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
199 DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
200 return isBlock ? divClose : styleSpanClose;
203 String StyledMarkupAccumulator::takeResults()
205 StringBuilder result;
206 result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length());
208 for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
209 result.append(m_reversedPrecedingMarkup[i - 1]);
211 concatenateMarkup(result);
213 // We remove '\0' characters because they are not visibly rendered to the user.
214 return result.toString().replace(0, "");
217 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text* text)
219 const bool parentIsTextarea = text->parentElement() && text->parentElement()->tagQName() == textareaTag;
220 const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
222 RefPtr<EditingStyle> wrappingStyle = m_wrappingStyle->copy();
223 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
224 // Make sure spans are inline style in paste side e.g. span { display: block }.
225 wrappingStyle->forceInline();
226 // FIXME: Should this be included in forceInline?
227 wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
229 appendStyleNodeOpenTag(out, wrappingStyle->style(), &text->document());
232 if (!shouldAnnotate() || parentIsTextarea)
233 MarkupAccumulator::appendText(out, text);
235 const bool useRenderedText = !enclosingNodeWithTag(firstPositionInNode(text), selectTag);
236 String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range);
237 StringBuilder buffer;
238 appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA);
239 out.append(convertHTMLTextToInterchangeFormat(buffer.toString(), text));
243 out.append(styleNodeCloseTag());
246 String StyledMarkupAccumulator::renderedText(const Node* node, const Range* range)
248 if (!node->isTextNode())
251 const Text* textNode = toText(node);
252 unsigned startOffset = 0;
253 unsigned endOffset = textNode->length();
255 if (range && node == range->startContainer())
256 startOffset = range->startOffset();
257 if (range && node == range->endContainer())
258 endOffset = range->endOffset();
260 Position start = createLegacyEditingPosition(const_cast<Node*>(node), startOffset);
261 Position end = createLegacyEditingPosition(const_cast<Node*>(node), endOffset);
262 return plainText(Range::create(node->document(), start, end).get());
265 String StyledMarkupAccumulator::stringValueForRange(const Node* node, const Range* range)
268 return node->nodeValue();
270 String str = node->nodeValue();
271 if (node == range->endContainer())
272 str.truncate(range->endOffset());
273 if (node == range->startContainer())
274 str.remove(0, range->startOffset());
278 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element* element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
280 const bool documentIsHTML = element->document().isHTMLDocument();
281 appendOpenTag(out, element, 0);
283 const unsigned length = element->hasAttributes() ? element->attributeCount() : 0;
284 const bool shouldAnnotateOrForceInline = element->isHTMLElement() && (shouldAnnotate() || addDisplayInline);
285 const bool shouldOverrideStyleAttr = shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element);
286 for (unsigned i = 0; i < length; ++i) {
287 const Attribute* attribute = element->attributeItem(i);
288 // We'll handle the style attribute separately, below.
289 if (attribute->name() == styleAttr && shouldOverrideStyleAttr)
291 appendAttribute(out, element, *attribute, 0);
294 if (shouldOverrideStyleAttr) {
295 RefPtr<EditingStyle> newInlineStyle;
297 if (shouldApplyWrappingStyle(element)) {
298 newInlineStyle = m_wrappingStyle->copy();
299 newInlineStyle->removePropertiesInElementDefaultStyle(element);
300 newInlineStyle->removeStyleConflictingWithStyleOfNode(element);
302 newInlineStyle = EditingStyle::create();
304 if (element->isStyledElement() && element->inlineStyle())
305 newInlineStyle->overrideWithStyle(element->inlineStyle());
307 if (shouldAnnotateOrForceInline) {
308 if (shouldAnnotate())
309 newInlineStyle->mergeStyleFromRulesForSerialization(toHTMLElement(element));
311 if (addDisplayInline)
312 newInlineStyle->forceInline();
314 // If the node is not fully selected by the range, then we don't want to keep styles that affect its relationship to the nodes around it
315 // only the ones that affect it and the nodes within it.
316 if (rangeFullySelectsNode == DoesNotFullySelectNode && newInlineStyle->style())
317 newInlineStyle->style()->removeProperty(CSSPropertyFloat);
320 if (!newInlineStyle->isEmpty()) {
321 out.appendLiteral(" style=\"");
322 appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
327 appendCloseTag(out, element);
330 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
332 if (!m_highestNodeToBeSerialized) {
333 Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString);
334 m_highestNodeToBeSerialized = lastClosed;
337 if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode())
338 m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate());
340 return traverseNodesForSerialization(startNode, pastEnd, EmitString);
343 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
345 const bool shouldEmit = traversalMode == EmitString;
346 Vector<Node*> ancestorsToClose;
348 Node* lastClosed = 0;
349 for (Node* n = startNode; n != pastEnd; n = next) {
350 // According to <rdar://problem/5730668>, it is possible for n to blow
351 // past pastEnd and become null here. This shouldn't be possible.
352 // This null check will prevent crashes (but create too much markup)
353 // and the ASSERT will hopefully lead us to understanding the problem.
358 next = NodeTraversal::next(n);
359 bool openedTag = false;
361 if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
362 // Don't write out empty block containers that aren't fully selected.
365 if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
366 next = NodeTraversal::nextSkippingChildren(n);
367 // Don't skip over pastEnd.
368 if (pastEnd && pastEnd->isDescendantOf(n))
371 // Add the node to the markup if we're not skipping the descendants
375 // If node has no children, close the tag now.
376 if (!n->childNodeCount()) {
382 ancestorsToClose.append(n);
386 // If we didn't insert open tag and there's no more siblings or we're at the end of the traversal, take care of ancestors.
387 // FIXME: What happens if we just inserted open tag and reached the end?
388 if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
389 // Close up the ancestors.
390 while (!ancestorsToClose.isEmpty()) {
391 Node* ancestor = ancestorsToClose.last();
392 if (next != pastEnd && next->isDescendantOf(ancestor))
394 // Not at the end of the range, close ancestors up to sibling of next node.
396 appendEndTag(ancestor);
397 lastClosed = ancestor;
398 ancestorsToClose.removeLast();
401 // Surround the currently accumulated markup with markup for ancestors we never opened as we leave the subtree(s) rooted at those ancestors.
402 ContainerNode* nextParent = next ? next->parentNode() : 0;
403 if (next != pastEnd && n != nextParent) {
404 Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
405 for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
406 // All ancestors that aren't in the ancestorsToClose list should either be a) unrendered:
407 if (!parent->renderer())
409 // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
410 ASSERT(startNode->isDescendantOf(parent));
412 wrapWithNode(parent);
422 static bool isHTMLBlockElement(const Node* node)
424 return node->hasTagName(tdTag)
425 || node->hasTagName(thTag)
426 || isNonTableCellHTMLBlockElement(node);
429 static Node* ancestorToRetainStructureAndAppearanceForBlock(Node* commonAncestorBlock)
431 if (!commonAncestorBlock)
434 if (commonAncestorBlock->hasTagName(tbodyTag) || commonAncestorBlock->hasTagName(trTag)) {
435 ContainerNode* table = commonAncestorBlock->parentNode();
436 while (table && !isHTMLTableElement(table))
437 table = table->parentNode();
442 if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
443 return commonAncestorBlock;
448 static inline Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
450 return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor));
453 static inline Node* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor)
455 Node* commonAncestorBlock = enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement);
456 return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock);
459 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID)
463 RefPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
466 if (!value->isPrimitiveValue())
468 return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
471 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
473 VisiblePosition next = v.next();
474 Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
475 Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
476 // Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it.
477 return isEndOfParagraph(v) && isStartOfParagraph(next) && !(upstreamNode->hasTagName(brTag) && upstreamNode == downstreamNode);
480 static PassRefPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const Node* node)
482 if (!node->isHTMLElement())
485 // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle
486 // the non-const-ness of styleFromMatchedRulesForElement.
487 HTMLElement* element = const_cast<HTMLElement*>(toHTMLElement(node));
488 RefPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle());
489 style->mergeStyleFromRules(element);
490 return style.release();
493 static bool isElementPresentational(const Node* node)
495 return node->hasTagName(uTag) || node->hasTagName(sTag) || node->hasTagName(strikeTag)
496 || node->hasTagName(iTag) || node->hasTagName(emTag) || node->hasTagName(bTag) || node->hasTagName(strongTag);
499 static Node* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor)
501 Node* commonAncestor = range->commonAncestorContainer(IGNORE_EXCEPTION);
502 ASSERT(commonAncestor);
503 Node* specialCommonAncestor = 0;
504 if (shouldAnnotate == AnnotateForInterchange) {
505 // Include ancestors that aren't completely inside the range but are required to retain
506 // the structure and appearance of the copied markup.
507 specialCommonAncestor = ancestorToRetainStructureAndAppearance(commonAncestor);
509 if (Node* parentListNode = enclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isListItem)) {
510 if (WebCore::areRangesEqual(VisibleSelection::selectionFromContentsOfNode(parentListNode).toNormalizedRange().get(), range)) {
511 specialCommonAncestor = parentListNode->parentNode();
512 while (specialCommonAncestor && !isListElement(specialCommonAncestor))
513 specialCommonAncestor = specialCommonAncestor->parentNode();
517 // Retain the Mail quote level by including all ancestor mail block quotes.
518 if (Node* highestMailBlockquote = highestEnclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isMailBlockquote, CanCrossEditingBoundary))
519 specialCommonAncestor = highestMailBlockquote;
522 Node* checkAncestor = specialCommonAncestor ? specialCommonAncestor : commonAncestor;
523 if (checkAncestor->renderer()) {
524 Node* newSpecialCommonAncestor = highestEnclosingNodeOfType(firstPositionInNode(checkAncestor), &isElementPresentational, CanCrossEditingBoundary, constrainingAncestor);
525 if (newSpecialCommonAncestor)
526 specialCommonAncestor = newSpecialCommonAncestor;
529 // If a single tab is selected, commonAncestor will be a text node inside a tab span.
530 // If two or more tabs are selected, commonAncestor will be the tab span.
531 // In either case, if there is a specialCommonAncestor already, it will necessarily be above
532 // any tab span that needs to be included.
533 if (!specialCommonAncestor && isTabSpanTextNode(commonAncestor))
534 specialCommonAncestor = commonAncestor->parentNode();
535 if (!specialCommonAncestor && isTabSpanNode(commonAncestor))
536 specialCommonAncestor = commonAncestor;
538 if (Node *enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag))
539 specialCommonAncestor = enclosingAnchor;
541 return specialCommonAncestor;
544 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange?
545 // FIXME: At least, annotation and style info should probably not be included in range.markupString()
546 static String createMarkupInternal(Document& document, const Range* range, const Range* updatedRange, Vector<Node*>* nodes,
547 EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
550 ASSERT(updatedRange);
551 DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
553 bool collapsed = updatedRange->collapsed(ASSERT_NO_EXCEPTION);
555 return emptyString();
556 Node* commonAncestor = updatedRange->commonAncestorContainer(ASSERT_NO_EXCEPTION);
558 return emptyString();
560 document.updateLayoutIgnorePendingStylesheets();
562 Node* body = enclosingNodeWithTag(firstPositionInNode(commonAncestor), bodyTag);
563 Node* fullySelectedRoot = 0;
564 // FIXME: Do this for all fully selected blocks, not just the body.
565 if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range))
566 fullySelectedRoot = body;
567 Node* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange, shouldAnnotate, constrainingAncestor);
568 StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange, specialCommonAncestor);
569 Node* pastEnd = updatedRange->pastLastNode();
571 Node* startNode = updatedRange->firstNode();
572 VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY);
573 VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY);
574 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) {
575 if (visibleStart == visibleEnd.previous())
576 return interchangeNewlineString;
578 accumulator.appendString(interchangeNewlineString);
579 startNode = visibleStart.next().deepEquivalent().deprecatedNode();
581 if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0)
582 return interchangeNewlineString;
585 Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
587 if (specialCommonAncestor && lastClosed) {
588 // Also include all of the ancestors of lastClosed up to this special ancestor.
589 for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) {
590 if (ancestor == fullySelectedRoot && !convertBlocksToInlines) {
591 RefPtr<EditingStyle> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot);
593 // Bring the background attribute over, but not as an attribute because a background attribute on a div
594 // appears to have no effect.
595 if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue(CSSPropertyBackgroundImage))
596 && toElement(fullySelectedRoot)->hasAttribute(backgroundAttr))
597 fullySelectedRootStyle->style()->setProperty(CSSPropertyBackgroundImage, "url('" + toElement(fullySelectedRoot)->getAttribute(backgroundAttr) + "')");
599 if (fullySelectedRootStyle->style()) {
600 // Reset the CSS properties to avoid an assertion error in addStyleMarkup().
601 // This assertion is caused at least when we select all text of a <body> element whose
602 // 'text-decoration' property is "inherit", and copy it.
603 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration))
604 fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone);
605 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect))
606 fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
607 accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), &document, true);
610 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
611 // so that styles that affect the exterior of the node are not included.
612 accumulator.wrapWithNode(ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
615 nodes->append(ancestor);
617 lastClosed = ancestor;
619 if (ancestor == specialCommonAncestor)
624 // FIXME: The interchange newline should be placed in the block that it's in, not after all of the content, unconditionally.
625 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous()))
626 accumulator.appendString(interchangeNewlineString);
628 return accumulator.takeResults();
631 String createMarkup(const Range* range, Vector<Node*>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
634 return emptyString();
636 Document& document = range->ownerDocument();
637 const Range* updatedRange = range;
639 return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
642 PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
644 // We use a fake body element here to trick the HTML parser to using the InBody insertion mode.
645 RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document);
646 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
648 fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
650 if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
651 completeURLs(fragment.get(), baseURL);
653 return fragment.release();
656 static const char fragmentMarkerTag[] = "webkit-fragment-marker";
658 static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
660 for (Node* node = document->firstChild(); node; node = NodeTraversal::next(node)) {
661 if (node->nodeType() == Node::COMMENT_NODE && toCharacterData(node)->data() == fragmentMarkerTag) {
662 if (!nodeBeforeContext)
663 nodeBeforeContext = node;
665 nodeAfterContext = node;
673 static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, Node* nodeAfterContext)
676 for (RefPtr<Node> node = fragment->firstChild(); node; node = next) {
677 if (nodeBeforeContext->isDescendantOf(node.get())) {
678 next = NodeTraversal::next(node.get());
681 next = NodeTraversal::nextSkippingChildren(node.get());
682 ASSERT(!node->contains(nodeAfterContext));
683 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
684 if (nodeBeforeContext == node)
688 ASSERT(nodeAfterContext->parentNode());
689 for (RefPtr<Node> node = nodeAfterContext; node; node = next) {
690 next = NodeTraversal::nextSkippingChildren(node.get());
691 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
695 PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
696 const String& baseURL, ParserContentPolicy parserContentPolicy)
698 // FIXME: Need to handle the case where the markup already contains these markers.
700 StringBuilder taggedMarkup;
701 taggedMarkup.append(markup.left(fragmentStart));
702 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
703 taggedMarkup.append(markup.substring(fragmentStart, fragmentEnd - fragmentStart));
704 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
705 taggedMarkup.append(markup.substring(fragmentEnd));
707 RefPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
708 RefPtr<Document> taggedDocument = Document::create();
709 taggedDocument->setContextFeatures(document.contextFeatures());
711 // FIXME: It's not clear what this code is trying to do. It puts nodes as direct children of a
712 // Document that are not normally allowed by using the parser machinery.
713 taggedDocument->parserTakeAllChildrenFrom(*taggedFragment);
715 RefPtr<Node> nodeBeforeContext;
716 RefPtr<Node> nodeAfterContext;
717 if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
720 RefPtr<Range> range = Range::create(*taggedDocument.get(),
721 positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
722 positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
724 Node* commonAncestor = range->commonAncestorContainer(ASSERT_NO_EXCEPTION);
725 Node* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor);
727 // When there's a special common ancestor outside of the fragment, we must include it as well to
728 // preserve the structure and appearance of the fragment. For example, if the fragment contains
729 // TD, we need to include the enclosing TABLE tag as well.
730 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
731 if (specialCommonAncestor)
732 fragment->appendChild(specialCommonAncestor);
734 fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
736 trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
741 String createMarkup(const Node* node, EChildrenOnly childrenOnly, Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip)
746 MarkupAccumulator accumulator(nodes, shouldResolveURLs);
747 return accumulator.serializeNodes(const_cast<Node*>(node), childrenOnly, tagNamesToSkip);
750 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
752 Document& document = paragraph->document();
754 if (string.isEmpty()) {
755 paragraph->appendChild(createBlockPlaceholderElement(document));
759 ASSERT(string.find('\n') == kNotFound);
761 Vector<String> tabList;
762 string.split('\t', true, tabList);
763 String tabText = emptyString();
765 size_t numEntries = tabList.size();
766 for (size_t i = 0; i < numEntries; ++i) {
767 const String& s = tabList[i];
769 // append the non-tab textual part
771 if (!tabText.isEmpty()) {
772 paragraph->appendChild(createTabSpanElement(document, tabText));
773 tabText = emptyString();
775 RefPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
776 paragraph->appendChild(textNode.release());
779 // there is a tab after every entry, except the last entry
780 // (if the last character is a tab, the list gets an extra empty entry)
781 if (i + 1 != numEntries)
782 tabText.append('\t');
783 else if (!tabText.isEmpty())
784 paragraph->appendChild(createTabSpanElement(document, tabText));
790 bool isPlainTextMarkup(Node *node)
792 if (!node->isElementNode() || !node->hasTagName(divTag) || toElement(node)->hasAttributes())
795 if (node->childNodeCount() == 1 && (node->firstChild()->isTextNode() || (node->firstChild()->firstChild())))
798 return (node->childNodeCount() == 2 && isTabSpanTextNode(node->firstChild()->firstChild()) && node->firstChild()->nextSibling()->isTextNode());
801 static bool shouldPreserveNewline(const Range& range)
803 if (Node* node = range.firstNode()) {
804 if (RenderObject* renderer = node->renderer())
805 return renderer->style()->preserveNewline();
808 if (Node* node = range.startPosition().anchorNode()) {
809 if (RenderObject* renderer = node->renderer())
810 return renderer->style()->preserveNewline();
816 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
821 Document& document = context->ownerDocument();
822 RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
825 return fragment.release();
827 String string = text;
828 string.replace("\r\n", "\n");
829 string.replace('\r', '\n');
831 if (shouldPreserveNewline(*context)) {
832 fragment->appendChild(document.createTextNode(string));
833 if (string.endsWith('\n')) {
834 RefPtr<Element> element = createBreakElement(document);
835 element->setAttribute(classAttr, AppleInterchangeNewline);
836 fragment->appendChild(element.release());
838 return fragment.release();
841 // A string with no newlines gets added inline, rather than being put into a paragraph.
842 if (string.find('\n') == kNotFound) {
843 fillContainerFromString(fragment.get(), string);
844 return fragment.release();
847 // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
848 Node* blockNode = enclosingBlock(context->firstNode());
849 Element* block = toElement(blockNode);
850 bool useClonesOfEnclosingBlock = blockNode
851 && blockNode->isElementNode()
852 && !block->hasTagName(bodyTag)
853 && !isHTMLHtmlElement(block)
854 && block != editableRootForPosition(context->startPosition());
855 bool useLineBreak = enclosingTextFormControl(context->startPosition());
858 string.split('\n', true, list); // true gets us empty strings in the list
859 size_t numLines = list.size();
860 for (size_t i = 0; i < numLines; ++i) {
861 const String& s = list[i];
863 RefPtr<Element> element;
864 if (s.isEmpty() && i + 1 == numLines) {
865 // For last line, use the "magic BR" rather than a P.
866 element = createBreakElement(document);
867 element->setAttribute(classAttr, AppleInterchangeNewline);
868 } else if (useLineBreak) {
869 element = createBreakElement(document);
870 fillContainerFromString(fragment.get(), s);
872 if (useClonesOfEnclosingBlock)
873 element = block->cloneElementWithoutChildren();
875 element = createDefaultParagraphElement(document);
876 fillContainerFromString(element.get(), s);
878 fragment->appendChild(element.release());
880 return fragment.release();
883 PassRefPtr<DocumentFragment> createFragmentFromNodes(Document *document, const Vector<Node*>& nodes)
888 RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
890 size_t size = nodes.size();
891 for (size_t i = 0; i < size; ++i) {
892 RefPtr<Element> element = createDefaultParagraphElement(*document);
893 element->appendChild(nodes[i]);
894 fragment->appendChild(element.release());
897 return fragment.release();
900 String createFullMarkup(const Node* node)
905 Frame* frame = node->document().frame();
909 // FIXME: This is never "for interchange". Is that right?
910 String markupString = createMarkup(node, IncludeNode, 0);
911 Node::NodeType nodeType = node->nodeType();
912 if (nodeType != Node::DOCUMENT_NODE && nodeType != Node::DOCUMENT_TYPE_NODE)
913 markupString = frame->documentTypeString() + markupString;
918 String createFullMarkup(const Range* range)
923 Node* node = range->startContainer();
927 Frame* frame = node->document().frame();
931 // FIXME: This is always "for interchange". Is that right? See the previous method.
932 return frame->documentTypeString() + createMarkup(range, 0, AnnotateForInterchange);
935 String urlToMarkup(const KURL& url, const String& title)
937 StringBuilder markup;
938 markup.append("<a href=\"");
939 markup.append(url.string());
940 markup.append("\">");
941 MarkupAccumulator::appendCharactersReplacingEntities(markup, title, 0, title.length(), EntityMaskInPCDATA);
942 markup.append("</a>");
943 return markup.toString();
946 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& es)
948 Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
949 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
951 if (document.isHTMLDocument()) {
952 fragment->parseHTML(markup, contextElement, parserContentPolicy);
956 bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
958 es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "Node", "The provided markup is invalid XML, and therefore cannot be inserted into an XML document."));
961 return fragment.release();
964 PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
966 RefPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
968 if (sourceMIMEType == "text/html") {
969 // As far as I can tell, there isn't a spec for how transformToFragment is supposed to work.
970 // Based on the documentation I can find, it looks like we want to start parsing the fragment in the InBody insertion mode.
971 // Unfortunately, that's an implementation detail of the parser.
972 // We achieve that effect here by passing in a fake body element as context for the fragment.
973 RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
974 fragment->parseHTML(sourceString, fakeBody.get());
975 } else if (sourceMIMEType == "text/plain") {
976 fragment->parserAppendChild(Text::create(outputDoc, sourceString));
978 bool successfulParse = fragment->parseXML(sourceString, 0);
979 if (!successfulParse)
983 // FIXME: Do we need to mess with URLs here?
985 return fragment.release();
988 static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
990 RefPtr<Node> nextChild;
991 for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) {
992 nextChild = child->nextSibling();
993 element->removeChild(child.get());
994 fragment->insertBefore(child, element);
996 fragment->removeChild(element);
999 PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& es)
1002 if (element->ieForbidsInsertHTML() || element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
1003 || element->hasLocalName(headTag) || element->hasLocalName(styleTag) || element->hasLocalName(titleTag)) {
1004 es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container is '" + element->localName() + "', which is not supported."));
1008 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", es);
1012 // We need to pop <html> and <body> elements and remove <head> to
1013 // accommodate folks passing complete HTML documents to make the
1014 // child of an element.
1016 RefPtr<Node> nextNode;
1017 for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
1018 nextNode = node->nextSibling();
1019 if (isHTMLHtmlElement(node.get()) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
1020 HTMLElement* element = toHTMLElement(node);
1021 if (Node* firstChild = element->firstChild())
1022 nextNode = firstChild;
1023 removeElementPreservingChildren(fragment, element);
1026 return fragment.release();
1029 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& es)
1032 RefPtr<ContainerNode> containerNode(container);
1034 ChildListMutationScope mutation(*containerNode);
1036 if (!fragment->firstChild()) {
1037 containerNode->removeChildren();
1041 if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) {
1042 toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data());
1046 if (containerNode->hasOneChild()) {
1047 containerNode->replaceChild(fragment, containerNode->firstChild(), es);
1051 containerNode->removeChildren();
1052 containerNode->appendChild(fragment, es);
1055 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& es)
1058 RefPtr<ContainerNode> containerNode(container);
1060 ChildListMutationScope mutation(*containerNode);
1062 if (containerNode->hasOneTextChild()) {
1063 toText(containerNode->firstChild())->setData(text);
1067 RefPtr<Text> textNode = Text::create(containerNode->document(), text);
1069 if (containerNode->hasOneChild()) {
1070 containerNode->replaceChild(textNode.release(), containerNode->firstChild(), es);
1074 containerNode->removeChildren();
1075 containerNode->appendChild(textNode.release(), es);
1078 void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& es)
1080 ASSERT(node && node->isTextNode());
1081 Node* next = node->nextSibling();
1082 if (!next || !next->isTextNode())
1085 RefPtr<Text> textNode = toText(node.get());
1086 RefPtr<Text> textNext = toText(next);
1087 textNode->appendData(textNext->data());
1088 if (textNext->parentNode()) // Might have been removed by mutation event.
1089 textNext->remove(es);