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 "bindings/core/v8/ExceptionState.h"
33 #include "core/CSSPropertyNames.h"
34 #include "core/CSSValueKeywords.h"
35 #include "core/HTMLNames.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/Comment.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/frame/LocalFrame.h"
55 #include "core/html/HTMLAnchorElement.h"
56 #include "core/html/HTMLBRElement.h"
57 #include "core/html/HTMLBodyElement.h"
58 #include "core/html/HTMLDivElement.h"
59 #include "core/html/HTMLElement.h"
60 #include "core/html/HTMLQuoteElement.h"
61 #include "core/html/HTMLSpanElement.h"
62 #include "core/html/HTMLTableCellElement.h"
63 #include "core/html/HTMLTableElement.h"
64 #include "core/html/HTMLTextFormControlElement.h"
65 #include "core/rendering/RenderObject.h"
66 #include "platform/weborigin/KURL.h"
67 #include "wtf/StdLibExtras.h"
68 #include "wtf/text/StringBuilder.h"
72 using namespace HTMLNames;
74 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID);
76 class AttributeChange {
77 ALLOW_ONLY_INLINE_ALLOCATION();
80 : m_name(nullAtom, nullAtom, nullAtom)
84 AttributeChange(PassRefPtrWillBeRawPtr<Element> element, const QualifiedName& name, const String& value)
85 : m_element(element), m_name(name), m_value(value)
91 m_element->setAttribute(m_name, AtomicString(m_value));
94 void trace(Visitor* visitor)
96 visitor->trace(m_element);
100 RefPtrWillBeMember<Element> m_element;
101 QualifiedName m_name;
107 WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::AttributeChange);
111 static void completeURLs(DocumentFragment& fragment, const String& baseURL)
113 WillBeHeapVector<AttributeChange> changes;
115 KURL parsedBaseURL(ParsedURLString, baseURL);
117 for (Element& element : ElementTraversal::descendantsOf(fragment)) {
118 AttributeCollection attributes = element.attributes();
119 // AttributeCollection::iterator end = attributes.end();
120 for (const auto& attribute : attributes) {
121 if (element.isURLAttribute(attribute) && !attribute.value().isEmpty())
122 changes.append(AttributeChange(&element, attribute.name(), KURL(parsedBaseURL, attribute.value()).string()));
126 for (auto& change : changes)
130 class StyledMarkupAccumulator final : public MarkupAccumulator {
132 enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
134 StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs, EAnnotateForInterchange, RawPtr<const Range>, Node* highestNodeToBeSerialized = nullptr);
135 Node* serializeNodes(Node* startNode, Node* pastEnd);
136 void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
137 void wrapWithNode(ContainerNode&, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
138 void wrapWithStyleNode(StylePropertySet*, const Document&, bool isBlock = false);
139 String takeResults();
142 void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, const Document&, bool isBlock = false);
143 const String& styleNodeCloseTag(bool isBlock = false);
144 virtual void appendText(StringBuilder& out, Text&) override;
145 String renderedText(Node&, const Range*);
146 String stringValueForRange(const Node&, const Range*);
147 void appendElement(StringBuilder& out, Element&, bool addDisplayInline, RangeFullySelectsNode);
148 virtual void appendElement(StringBuilder& out, Element& element, Namespaces*) override { appendElement(out, element, false, DoesFullySelectNode); }
150 enum NodeTraversalMode { EmitString, DoNotEmitString };
151 Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
153 bool shouldAnnotate() const { return m_shouldAnnotate == AnnotateForInterchange || m_shouldAnnotate == AnnotateForNavigationTransition; }
154 bool shouldApplyWrappingStyle(const Node& node) const
156 return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode()
157 && m_wrappingStyle && m_wrappingStyle->style();
160 Vector<String> m_reversedPrecedingMarkup;
161 const EAnnotateForInterchange m_shouldAnnotate;
162 RawPtrWillBeMember<Node> m_highestNodeToBeSerialized;
163 RefPtrWillBeMember<EditingStyle> m_wrappingStyle;
166 inline StyledMarkupAccumulator::StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate, RawPtr<const Range> range, Node* highestNodeToBeSerialized)
167 : MarkupAccumulator(nodes, shouldResolveURLs, range)
168 , m_shouldAnnotate(shouldAnnotate)
169 , m_highestNodeToBeSerialized(highestNodeToBeSerialized)
173 void StyledMarkupAccumulator::wrapWithNode(ContainerNode& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
175 StringBuilder markup;
176 if (node.isElementNode())
177 appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode);
179 appendStartMarkup(markup, node, 0);
180 m_reversedPrecedingMarkup.append(markup.toString());
181 if (node.isElementNode())
182 appendEndTag(toElement(node));
184 m_nodes->append(&node);
187 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock)
189 StringBuilder openTag;
190 appendStyleNodeOpenTag(openTag, style, document, isBlock);
191 m_reversedPrecedingMarkup.append(openTag.toString());
192 appendString(styleNodeCloseTag(isBlock));
195 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock)
197 // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
198 ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
200 out.appendLiteral("<div style=\"");
202 out.appendLiteral("<span style=\"");
203 appendAttributeValue(out, style->asText(), document.isHTMLDocument());
204 out.appendLiteral("\">");
207 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
209 DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
210 DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
211 return isBlock ? divClose : styleSpanClose;
214 String StyledMarkupAccumulator::takeResults()
216 StringBuilder result;
217 result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length());
219 for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
220 result.append(m_reversedPrecedingMarkup[i - 1]);
222 concatenateMarkup(result);
224 // We remove '\0' characters because they are not visibly rendered to the user.
225 return result.toString().replace(0, "");
228 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text)
230 const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag;
231 const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
233 RefPtrWillBeRawPtr<EditingStyle> wrappingStyle = m_wrappingStyle->copy();
234 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
235 // Make sure spans are inline style in paste side e.g. span { display: block }.
236 wrappingStyle->forceInline();
237 // FIXME: Should this be included in forceInline?
238 wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
240 appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document());
243 if (!shouldAnnotate() || parentIsTextarea)
244 MarkupAccumulator::appendText(out, text);
246 const bool useRenderedText = !enclosingElementWithTag(firstPositionInNode(&text), selectTag);
247 String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range);
248 StringBuilder buffer;
249 appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA);
250 out.append(convertHTMLTextToInterchangeFormat(buffer.toString(), text));
254 out.append(styleNodeCloseTag());
257 String StyledMarkupAccumulator::renderedText(Node& node, const Range* range)
259 if (!node.isTextNode())
262 Text& textNode = toText(node);
263 unsigned startOffset = 0;
264 unsigned endOffset = textNode.length();
266 if (range && textNode == range->startContainer())
267 startOffset = range->startOffset();
268 if (range && textNode == range->endContainer())
269 endOffset = range->endOffset();
271 Position start = createLegacyEditingPosition(&textNode, startOffset);
272 Position end = createLegacyEditingPosition(&textNode, endOffset);
273 return plainText(Range::create(textNode.document(), start, end).get());
276 String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
279 return node.nodeValue();
281 String str = node.nodeValue();
282 if (node == range->endContainer())
283 str.truncate(range->endOffset());
284 if (node == range->startContainer())
285 str.remove(0, range->startOffset());
289 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
291 const bool documentIsHTML = element.document().isHTMLDocument();
292 appendOpenTag(out, element, 0);
294 const bool shouldAnnotateOrForceInline = element.isHTMLElement() && (shouldAnnotate() || addDisplayInline);
295 const bool shouldOverrideStyleAttr = shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element);
297 AttributeCollection attributes = element.attributes();
298 for (const auto& attribute : attributes) {
299 // We'll handle the style attribute separately, below.
300 if (attribute.name() == styleAttr && shouldOverrideStyleAttr)
302 appendAttribute(out, element, attribute, 0);
305 if (shouldOverrideStyleAttr) {
306 RefPtrWillBeRawPtr<EditingStyle> newInlineStyle = nullptr;
308 if (shouldApplyWrappingStyle(element)) {
309 newInlineStyle = m_wrappingStyle->copy();
310 newInlineStyle->removePropertiesInElementDefaultStyle(&element);
311 newInlineStyle->removeStyleConflictingWithStyleOfElement(&element);
313 newInlineStyle = EditingStyle::create();
315 if (element.isStyledElement() && element.inlineStyle())
316 newInlineStyle->overrideWithStyle(element.inlineStyle());
318 if (shouldAnnotateOrForceInline) {
319 if (shouldAnnotate())
320 newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element));
322 if (&element == m_highestNodeToBeSerialized && m_shouldAnnotate == AnnotateForNavigationTransition)
323 newInlineStyle->addAbsolutePositioningFromElement(element);
325 if (addDisplayInline)
326 newInlineStyle->forceInline();
328 // 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
329 // only the ones that affect it and the nodes within it.
330 if (rangeFullySelectsNode == DoesNotFullySelectNode && newInlineStyle->style())
331 newInlineStyle->style()->removeProperty(CSSPropertyFloat);
334 if (!newInlineStyle->isEmpty()) {
335 out.appendLiteral(" style=\"");
336 appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
341 appendCloseTag(out, element);
344 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
346 if (!m_highestNodeToBeSerialized) {
347 Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString);
348 m_highestNodeToBeSerialized = lastClosed;
351 if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode()) {
352 m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate());
353 if (m_shouldAnnotate == AnnotateForNavigationTransition) {
354 m_wrappingStyle->style()->removeProperty(CSSPropertyBackgroundColor);
355 m_wrappingStyle->style()->removeProperty(CSSPropertyBackgroundImage);
360 return traverseNodesForSerialization(startNode, pastEnd, EmitString);
363 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
365 const bool shouldEmit = traversalMode == EmitString;
366 WillBeHeapVector<RawPtrWillBeMember<ContainerNode>> ancestorsToClose;
368 Node* lastClosed = nullptr;
369 for (Node* n = startNode; n != pastEnd; n = next) {
370 // According to <rdar://problem/5730668>, it is possible for n to blow
371 // past pastEnd and become null here. This shouldn't be possible.
372 // This null check will prevent crashes (but create too much markup)
373 // and the ASSERT will hopefully lead us to understanding the problem.
378 next = NodeTraversal::next(*n);
379 bool openedTag = false;
381 if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
382 // Don't write out empty block containers that aren't fully selected.
385 if (!n->renderer() && !enclosingElementWithTag(firstPositionInOrBeforeNode(n), selectTag) && m_shouldAnnotate != AnnotateForNavigationTransition) {
386 next = NodeTraversal::nextSkippingChildren(*n);
387 // Don't skip over pastEnd.
388 if (pastEnd && pastEnd->isDescendantOf(n))
391 // Add the node to the markup if we're not skipping the descendants
395 // If node has no children, close the tag now.
396 if (n->isContainerNode() && toContainerNode(n)->hasChildren()) {
398 ancestorsToClose.append(toContainerNode(n));
400 if (shouldEmit && n->isElementNode())
401 appendEndTag(toElement(*n));
406 // 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.
407 // FIXME: What happens if we just inserted open tag and reached the end?
408 if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
409 // Close up the ancestors.
410 while (!ancestorsToClose.isEmpty()) {
411 ContainerNode* ancestor = ancestorsToClose.last();
413 if (next != pastEnd && next->isDescendantOf(ancestor))
415 // Not at the end of the range, close ancestors up to sibling of next node.
416 if (shouldEmit && ancestor->isElementNode())
417 appendEndTag(toElement(*ancestor));
418 lastClosed = ancestor;
419 ancestorsToClose.removeLast();
422 // Surround the currently accumulated markup with markup for ancestors we never opened as we leave the subtree(s) rooted at those ancestors.
423 ContainerNode* nextParent = next ? next->parentNode() : 0;
424 if (next != pastEnd && n != nextParent) {
425 Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
426 for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
427 // All ancestors that aren't in the ancestorsToClose list should either be a) unrendered:
428 if (!parent->renderer())
430 // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
431 ASSERT(startNode->isDescendantOf(parent));
433 wrapWithNode(*parent);
443 static bool isHTMLBlockElement(const Node* node)
446 return isHTMLTableCellElement(*node)
447 || isNonTableCellHTMLBlockElement(node);
450 static HTMLElement* ancestorToRetainStructureAndAppearanceForBlock(Element* commonAncestorBlock)
452 if (!commonAncestorBlock)
455 if (commonAncestorBlock->hasTagName(tbodyTag) || isHTMLTableRowElement(*commonAncestorBlock))
456 return Traversal<HTMLTableElement>::firstAncestor(*commonAncestorBlock);
458 if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
459 return toHTMLElement(commonAncestorBlock);
464 static inline HTMLElement* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
466 return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor));
469 static inline HTMLElement* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor)
471 HTMLElement* commonAncestorBlock = toHTMLElement(enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement));
472 return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock);
475 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID)
479 RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
482 if (!value->isPrimitiveValue())
484 return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
487 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
489 VisiblePosition next = v.next();
490 Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
491 Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
492 // Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it.
493 return isEndOfParagraph(v) && isStartOfParagraph(next) && !(isHTMLBRElement(*upstreamNode) && upstreamNode == downstreamNode);
496 static PassRefPtrWillBeRawPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const HTMLElement* element)
498 RefPtrWillBeRawPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle());
499 // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle
500 // the non-const-ness of styleFromMatchedRulesForElement.
501 style->mergeStyleFromRules(const_cast<HTMLElement*>(element));
502 return style.release();
505 static bool isPresentationalHTMLElement(const Node* node)
507 if (!node->isHTMLElement())
510 const HTMLElement& element = toHTMLElement(*node);
511 return element.hasTagName(uTag) || element.hasTagName(sTag) || element.hasTagName(strikeTag)
512 || element.hasTagName(iTag) || element.hasTagName(emTag) || element.hasTagName(bTag) || element.hasTagName(strongTag);
515 static HTMLElement* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor)
517 Node* commonAncestor = range->commonAncestorContainer();
518 ASSERT(commonAncestor);
519 HTMLElement* specialCommonAncestor = nullptr;
520 if (shouldAnnotate == AnnotateForInterchange) {
521 // Include ancestors that aren't completely inside the range but are required to retain
522 // the structure and appearance of the copied markup.
523 specialCommonAncestor = ancestorToRetainStructureAndAppearance(commonAncestor);
525 if (Node* parentListNode = enclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isListItem)) {
526 if (blink::areRangesEqual(VisibleSelection::selectionFromContentsOfNode(parentListNode).toNormalizedRange().get(), range)) {
527 ContainerNode* ancestor = parentListNode->parentNode();
528 while (ancestor && !isHTMLListElement(ancestor))
529 ancestor = ancestor->parentNode();
530 specialCommonAncestor = toHTMLElement(ancestor);
534 // Retain the Mail quote level by including all ancestor mail block quotes.
535 if (HTMLQuoteElement* highestMailBlockquote = toHTMLQuoteElement(highestEnclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isMailHTMLBlockquoteElement, CanCrossEditingBoundary)))
536 specialCommonAncestor = highestMailBlockquote;
539 Node* checkAncestor = specialCommonAncestor ? specialCommonAncestor : commonAncestor;
540 if (checkAncestor->renderer()) {
541 HTMLElement* newSpecialCommonAncestor = toHTMLElement(highestEnclosingNodeOfType(firstPositionInNode(checkAncestor), &isPresentationalHTMLElement, CanCrossEditingBoundary, constrainingAncestor));
542 if (newSpecialCommonAncestor)
543 specialCommonAncestor = newSpecialCommonAncestor;
546 // If a single tab is selected, commonAncestor will be a text node inside a tab span.
547 // If two or more tabs are selected, commonAncestor will be the tab span.
548 // In either case, if there is a specialCommonAncestor already, it will necessarily be above
549 // any tab span that needs to be included.
550 if (!specialCommonAncestor && isTabHTMLSpanElementTextNode(commonAncestor))
551 specialCommonAncestor = toHTMLSpanElement(commonAncestor->parentNode());
552 if (!specialCommonAncestor && isTabHTMLSpanElement(commonAncestor))
553 specialCommonAncestor = toHTMLSpanElement(commonAncestor);
555 if (HTMLAnchorElement* enclosingAnchor = toHTMLAnchorElement(enclosingElementWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag)))
556 specialCommonAncestor = enclosingAnchor;
558 return specialCommonAncestor;
561 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange?
562 // FIXME: At least, annotation and style info should probably not be included in range.markupString()
563 static String createMarkupInternal(Document& document, const Range* range, const Range* updatedRange, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes,
564 EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
567 ASSERT(updatedRange);
568 DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
570 bool collapsed = updatedRange->collapsed();
572 return emptyString();
573 Node* commonAncestor = updatedRange->commonAncestorContainer();
575 return emptyString();
577 document.updateLayoutIgnorePendingStylesheets();
579 HTMLBodyElement* body = toHTMLBodyElement(enclosingElementWithTag(firstPositionInNode(commonAncestor), bodyTag));
580 HTMLBodyElement* fullySelectedRoot = nullptr;
581 // FIXME: Do this for all fully selected blocks, not just the body.
582 if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range))
583 fullySelectedRoot = body;
584 HTMLElement* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange, shouldAnnotate, constrainingAncestor);
585 StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange, specialCommonAncestor);
586 Node* pastEnd = updatedRange->pastLastNode();
588 Node* startNode = updatedRange->firstNode();
589 VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY);
590 VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY);
591 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) {
592 if (visibleStart == visibleEnd.previous())
593 return interchangeNewlineString;
595 accumulator.appendString(interchangeNewlineString);
596 startNode = visibleStart.next().deepEquivalent().deprecatedNode();
598 if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0)
599 return interchangeNewlineString;
602 Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
604 if (specialCommonAncestor && lastClosed) {
605 // Also include all of the ancestors of lastClosed up to this special ancestor.
606 for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) {
607 if (ancestor == fullySelectedRoot && !convertBlocksToInlines) {
608 RefPtrWillBeRawPtr<EditingStyle> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot);
610 // Bring the background attribute over, but not as an attribute because a background attribute on a div
611 // appears to have no effect.
612 if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue(CSSPropertyBackgroundImage))
613 && fullySelectedRoot->hasAttribute(backgroundAttr))
614 fullySelectedRootStyle->style()->setProperty(CSSPropertyBackgroundImage, "url('" + fullySelectedRoot->getAttribute(backgroundAttr) + "')");
616 if (fullySelectedRootStyle->style()) {
617 // Reset the CSS properties to avoid an assertion error in addStyleMarkup().
618 // This assertion is caused at least when we select all text of a <body> element whose
619 // 'text-decoration' property is "inherit", and copy it.
620 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration))
621 fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone);
622 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect))
623 fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
624 accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true);
627 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
628 // so that styles that affect the exterior of the node are not included.
629 accumulator.wrapWithNode(*ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
632 nodes->append(ancestor);
634 if (ancestor == specialCommonAncestor)
639 // FIXME: The interchange newline should be placed in the block that it's in, not after all of the content, unconditionally.
640 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous()))
641 accumulator.appendString(interchangeNewlineString);
643 return accumulator.takeResults();
646 String createMarkup(const Range* range, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
649 return emptyString();
651 Document& document = range->ownerDocument();
652 const Range* updatedRange = range;
654 return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
657 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
659 // We use a fake body element here to trick the HTML parser to using the InBody insertion mode.
660 RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document);
661 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
663 fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
665 if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
666 completeURLs(*fragment, baseURL);
668 return fragment.release();
671 static const char fragmentMarkerTag[] = "webkit-fragment-marker";
673 static bool findNodesSurroundingContext(Document* document, RefPtrWillBeRawPtr<Comment>& nodeBeforeContext, RefPtrWillBeRawPtr<Comment>& nodeAfterContext)
675 for (Node& node : NodeTraversal::startsAt(document->firstChild())) {
676 if (node.nodeType() == Node::COMMENT_NODE && toComment(node).data() == fragmentMarkerTag) {
677 if (!nodeBeforeContext)
678 nodeBeforeContext = &toComment(node);
680 nodeAfterContext = &toComment(node);
688 static void trimFragment(DocumentFragment* fragment, Comment* nodeBeforeContext, Comment* nodeAfterContext)
690 RefPtrWillBeRawPtr<Node> next = nullptr;
691 for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = next) {
692 if (nodeBeforeContext->isDescendantOf(node.get())) {
693 next = NodeTraversal::next(*node);
696 next = NodeTraversal::nextSkippingChildren(*node);
697 ASSERT(!node->contains(nodeAfterContext));
698 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
699 if (nodeBeforeContext == node)
703 ASSERT(nodeAfterContext->parentNode());
704 for (RefPtrWillBeRawPtr<Node> node = nodeAfterContext; node; node = next) {
705 next = NodeTraversal::nextSkippingChildren(*node);
706 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
710 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
711 const String& baseURL, ParserContentPolicy parserContentPolicy)
713 // FIXME: Need to handle the case where the markup already contains these markers.
715 StringBuilder taggedMarkup;
716 taggedMarkup.append(markup.left(fragmentStart));
717 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
718 taggedMarkup.append(markup.substring(fragmentStart, fragmentEnd - fragmentStart));
719 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag);
720 taggedMarkup.append(markup.substring(fragmentEnd));
722 RefPtrWillBeRawPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
723 RefPtrWillBeRawPtr<Document> taggedDocument = Document::create();
724 taggedDocument->setContextFeatures(document.contextFeatures());
726 // FIXME: It's not clear what this code is trying to do. It puts nodes as direct children of a
727 // Document that are not normally allowed by using the parser machinery.
728 taggedDocument->parserTakeAllChildrenFrom(*taggedFragment);
730 RefPtrWillBeRawPtr<Comment> nodeBeforeContext = nullptr;
731 RefPtrWillBeRawPtr<Comment> nodeAfterContext = nullptr;
732 if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
735 RefPtrWillBeRawPtr<Range> range = Range::create(*taggedDocument.get(),
736 positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
737 positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
739 Node* commonAncestor = range->commonAncestorContainer();
740 HTMLElement* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor);
742 // When there's a special common ancestor outside of the fragment, we must include it as well to
743 // preserve the structure and appearance of the fragment. For example, if the fragment contains
744 // TD, we need to include the enclosing TABLE tag as well.
745 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
746 if (specialCommonAncestor)
747 fragment->appendChild(specialCommonAncestor);
749 fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
751 trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
756 String createMarkup(const Node* node, EChildrenOnly childrenOnly, WillBeHeapVector<RawPtrWillBeMember<Node>>* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip)
761 MarkupAccumulator accumulator(nodes, shouldResolveURLs);
762 return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip);
765 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
767 Document& document = paragraph->document();
769 if (string.isEmpty()) {
770 paragraph->appendChild(createBlockPlaceholderElement(document));
774 ASSERT(string.find('\n') == kNotFound);
776 Vector<String> tabList;
777 string.split('\t', true, tabList);
778 StringBuilder tabText;
780 size_t numEntries = tabList.size();
781 for (size_t i = 0; i < numEntries; ++i) {
782 const String& s = tabList[i];
784 // append the non-tab textual part
786 if (!tabText.isEmpty()) {
787 paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
790 RefPtrWillBeRawPtr<Text> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
791 paragraph->appendChild(textNode.release());
794 // there is a tab after every entry, except the last entry
795 // (if the last character is a tab, the list gets an extra empty entry)
796 if (i + 1 != numEntries)
797 tabText.append('\t');
798 else if (!tabText.isEmpty())
799 paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
805 bool isPlainTextMarkup(Node* node)
808 if (!isHTMLDivElement(*node))
811 HTMLDivElement& element = toHTMLDivElement(*node);
812 if (!element.hasAttributes())
815 if (element.hasOneChild())
816 return element.firstChild()->isTextNode() || element.firstChild()->hasChildren();
818 return element.hasChildCount(2) && isTabHTMLSpanElementTextNode(element.firstChild()->firstChild()) && element.lastChild()->isTextNode();
821 static bool shouldPreserveNewline(const Range& range)
823 if (Node* node = range.firstNode()) {
824 if (RenderObject* renderer = node->renderer())
825 return renderer->style()->preserveNewline();
828 if (Node* node = range.startPosition().anchorNode()) {
829 if (RenderObject* renderer = node->renderer())
830 return renderer->style()->preserveNewline();
836 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
841 Document& document = context->ownerDocument();
842 RefPtrWillBeRawPtr<DocumentFragment> fragment = document.createDocumentFragment();
845 return fragment.release();
847 String string = text;
848 string.replace("\r\n", "\n");
849 string.replace('\r', '\n');
851 if (shouldPreserveNewline(*context)) {
852 fragment->appendChild(document.createTextNode(string));
853 if (string.endsWith('\n')) {
854 RefPtrWillBeRawPtr<HTMLBRElement> element = createBreakElement(document);
855 element->setAttribute(classAttr, AppleInterchangeNewline);
856 fragment->appendChild(element.release());
858 return fragment.release();
861 // A string with no newlines gets added inline, rather than being put into a paragraph.
862 if (string.find('\n') == kNotFound) {
863 fillContainerFromString(fragment.get(), string);
864 return fragment.release();
867 // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
868 Element* block = enclosingBlock(context->firstNode());
869 bool useClonesOfEnclosingBlock = block
870 && !isHTMLBodyElement(*block)
871 && !isHTMLHtmlElement(*block)
872 && block != editableRootForPosition(context->startPosition());
873 bool useLineBreak = enclosingTextFormControl(context->startPosition());
876 string.split('\n', true, list); // true gets us empty strings in the list
877 size_t numLines = list.size();
878 for (size_t i = 0; i < numLines; ++i) {
879 const String& s = list[i];
881 RefPtrWillBeRawPtr<Element> element = nullptr;
882 if (s.isEmpty() && i + 1 == numLines) {
883 // For last line, use the "magic BR" rather than a P.
884 element = createBreakElement(document);
885 element->setAttribute(classAttr, AppleInterchangeNewline);
886 } else if (useLineBreak) {
887 element = createBreakElement(document);
888 fillContainerFromString(fragment.get(), s);
890 if (useClonesOfEnclosingBlock)
891 element = block->cloneElementWithoutChildren();
893 element = createDefaultParagraphElement(document);
894 fillContainerFromString(element.get(), s);
896 fragment->appendChild(element.release());
898 return fragment.release();
901 String urlToMarkup(const KURL& url, const String& title)
903 StringBuilder markup;
904 markup.appendLiteral("<a href=\"");
905 markup.append(url.string());
906 markup.appendLiteral("\">");
907 MarkupAccumulator::appendCharactersReplacingEntities(markup, title, 0, title.length(), EntityMaskInPCDATA);
908 markup.appendLiteral("</a>");
909 return markup.toString();
912 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
914 ASSERT(contextElement);
915 Document& document = isHTMLTemplateElement(*contextElement) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
916 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document);
918 if (document.isHTMLDocument()) {
919 fragment->parseHTML(markup, contextElement, parserContentPolicy);
923 bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
925 exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document.");
928 return fragment.release();
931 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
933 RefPtrWillBeRawPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
935 if (sourceMIMEType == "text/html") {
936 // As far as I can tell, there isn't a spec for how transformToFragment is supposed to work.
937 // Based on the documentation I can find, it looks like we want to start parsing the fragment in the InBody insertion mode.
938 // Unfortunately, that's an implementation detail of the parser.
939 // We achieve that effect here by passing in a fake body element as context for the fragment.
940 RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
941 fragment->parseHTML(sourceString, fakeBody.get());
942 } else if (sourceMIMEType == "text/plain") {
943 fragment->parserAppendChild(Text::create(outputDoc, sourceString));
945 bool successfulParse = fragment->parseXML(sourceString, 0);
946 if (!successfulParse)
950 // FIXME: Do we need to mess with URLs here?
952 return fragment.release();
955 static inline void removeElementPreservingChildren(PassRefPtrWillBeRawPtr<DocumentFragment> fragment, HTMLElement* element)
957 RefPtrWillBeRawPtr<Node> nextChild = nullptr;
958 for (RefPtrWillBeRawPtr<Node> child = element->firstChild(); child; child = nextChild) {
959 nextChild = child->nextSibling();
960 element->removeChild(child.get());
961 fragment->insertBefore(child, element);
963 fragment->removeChild(element);
966 static inline bool isSupportedContainer(Element* element)
969 if (!element->isHTMLElement())
972 HTMLElement& htmlElement = toHTMLElement(*element);
973 if (htmlElement.hasTagName(colTag) || htmlElement.hasTagName(colgroupTag) || htmlElement.hasTagName(framesetTag)
974 || htmlElement.hasTagName(headTag) || htmlElement.hasTagName(styleTag) || htmlElement.hasTagName(titleTag)) {
977 return !htmlElement.ieForbidsInsertHTML();
980 PassRefPtrWillBeRawPtr<DocumentFragment> createContextualFragment(const String& markup, Element* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
983 if (!isSupportedContainer(element)) {
984 exceptionState.throwDOMException(NotSupportedError, "The range's container is '" + element->localName() + "', which is not supported.");
988 RefPtrWillBeRawPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
992 // We need to pop <html> and <body> elements and remove <head> to
993 // accommodate folks passing complete HTML documents to make the
994 // child of an element.
996 RefPtrWillBeRawPtr<Node> nextNode = nullptr;
997 for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
998 nextNode = node->nextSibling();
999 if (isHTMLHtmlElement(*node) || isHTMLHeadElement(*node) || isHTMLBodyElement(*node)) {
1000 HTMLElement* element = toHTMLElement(node);
1001 if (Node* firstChild = element->firstChild())
1002 nextNode = firstChild;
1003 removeElementPreservingChildren(fragment, element);
1006 return fragment.release();
1009 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtrWillBeRawPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
1012 RefPtrWillBeRawPtr<ContainerNode> containerNode(container);
1014 ChildListMutationScope mutation(*containerNode);
1016 if (!fragment->firstChild()) {
1017 containerNode->removeChildren();
1021 // FIXME: This is wrong if containerNode->firstChild() has more than one ref!
1022 if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) {
1023 toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data());
1027 // FIXME: No need to replace the child it is a text node and its contents are already == text.
1028 if (containerNode->hasOneChild()) {
1029 containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState);
1033 containerNode->removeChildren();
1034 containerNode->appendChild(fragment, exceptionState);
1037 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
1040 RefPtrWillBeRawPtr<ContainerNode> containerNode(container);
1042 ChildListMutationScope mutation(*containerNode);
1044 // FIXME: This is wrong if containerNode->firstChild() has more than one ref! Example:
1047 // var oldText = div.firstChild;
1048 // console.log(oldText.data); // foo
1049 // div.innerText = "bar";
1050 // console.log(oldText.data); // bar!?!
1052 // I believe this is an intentional benchmark cheat from years ago.
1053 // We should re-visit if we actually want this still.
1054 if (containerNode->hasOneTextChild()) {
1055 toText(containerNode->firstChild())->setData(text);
1059 // NOTE: This method currently always creates a text node, even if that text node will be empty.
1060 RefPtrWillBeRawPtr<Text> textNode = Text::create(containerNode->document(), text);
1062 // FIXME: No need to replace the child it is a text node and its contents are already == text.
1063 if (containerNode->hasOneChild()) {
1064 containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState);
1068 containerNode->removeChildren();
1069 containerNode->appendChild(textNode.release(), exceptionState);
1072 void mergeWithNextTextNode(Text* textNode, ExceptionState& exceptionState)
1075 Node* next = textNode->nextSibling();
1076 if (!next || !next->isTextNode())
1079 RefPtrWillBeRawPtr<Text> textNext = toText(next);
1080 textNode->appendData(textNext->data());
1081 if (textNext->parentNode()) // Might have been removed by mutation event.
1082 textNext->remove(exceptionState);
1085 String createStyledMarkupForNavigationTransition(Node* node)
1087 node->document().updateLayoutIgnorePendingStylesheets();
1089 StyledMarkupAccumulator accumulator(0, ResolveAllURLs, AnnotateForNavigationTransition, nullptr, 0);
1090 accumulator.serializeNodes(node, NodeTraversal::nextSkippingChildren(*node));
1092 static const char* documentMarkup = "<!DOCTYPE html><meta name=\"viewport\" content=\"width=device-width, user-scalable=0\">";
1093 return documentMarkup + accumulator.takeResults();