2 * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "ReplaceSelectionCommand.h"
29 #include "ApplyStyleCommand.h"
30 #include "BeforeTextInsertedEvent.h"
31 #include "CSSComputedStyleDeclaration.h"
32 #include "CSSPropertyNames.h"
34 #include "DocumentFragment.h"
35 #include "EditingText.h"
38 #include "HTMLElement.h"
39 #include "HTMLInterchange.h"
40 #include "HTMLNames.h"
41 #include "SelectionController.h"
42 #include "TextIterator.h"
43 #include "htmlediting.h"
45 #include "visible_units.h"
49 using namespace HTMLNames;
51 static bool isInterchangeNewlineNode(const Node *node)
53 static String interchangeNewlineClassString(AppleInterchangeNewline);
54 return node && node->hasTagName(brTag) &&
55 static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
58 static bool isInterchangeConvertedSpaceSpan(const Node *node)
60 static String convertedSpaceSpanClassString(AppleConvertedSpace);
61 return node->isHTMLElement() &&
62 static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
65 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const Selection& selection)
66 : m_document(document),
68 m_matchStyle(matchStyle),
69 m_hasInterchangeNewlineAtStart(false),
70 m_hasInterchangeNewlineAtEnd(false)
76 Node* firstChild = m_fragment->firstChild();
80 Element* editableRoot = selection.rootEditableElement();
85 Node* styleNode = selection.base().node();
86 RefPtr<Node> holder = insertFragmentForTestRendering(styleNode);
88 RefPtr<Range> range = Selection::selectionFromContentsOfNode(holder.get()).toRange();
89 String text = plainText(range.get());
90 // Give the root a chance to change the text.
91 RefPtr<BeforeTextInsertedEvent> evt = new BeforeTextInsertedEvent(text);
93 editableRoot->dispatchEvent(evt, ec, true);
95 if (text != evt->text() || !editableRoot->isContentRichlyEditable()) {
96 restoreTestRenderingNodesToFragment(holder.get());
99 m_fragment = createFragmentFromText(selection.toRange().get(), evt->text());
100 firstChild = m_fragment->firstChild();
103 holder = insertFragmentForTestRendering(styleNode);
106 Node *node = firstChild;
107 Node *newlineAtStartNode = 0;
108 Node *newlineAtEndNode = 0;
110 Node *next = node->traverseNextNode();
111 if (isInterchangeNewlineNode(node)) {
112 if (next || node == firstChild) {
113 m_hasInterchangeNewlineAtStart = true;
114 newlineAtStartNode = node;
117 m_hasInterchangeNewlineAtEnd = true;
118 newlineAtEndNode = node;
121 else if (isInterchangeConvertedSpaceSpan(node)) {
123 while ((n = node->firstChild())) {
125 insertNodeBefore(n.get(), node);
129 next = n->traverseNextNode();
134 if (newlineAtStartNode)
135 removeNode(newlineAtStartNode);
136 if (newlineAtEndNode)
137 removeNode(newlineAtEndNode);
139 removeUnrenderedNodes(holder.get());
140 restoreTestRenderingNodesToFragment(holder.get());
144 bool ReplacementFragment::isEmpty() const
146 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
149 Node *ReplacementFragment::firstChild() const
151 return m_fragment->firstChild();
154 Node *ReplacementFragment::lastChild() const
156 return m_fragment->lastChild();
159 void ReplacementFragment::removeNodePreservingChildren(Node *node)
164 while (RefPtr<Node> n = node->firstChild()) {
166 insertNodeBefore(n.get(), node);
171 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
176 Node *parent = node->parentNode();
180 ExceptionCode ec = 0;
181 parent->removeChild(node.get(), ec);
185 void ReplacementFragment::insertNodeBefore(Node *node, Node *refNode)
187 if (!node || !refNode)
190 Node *parent = refNode->parentNode();
194 ExceptionCode ec = 0;
195 parent->insertBefore(node, refNode, ec);
199 PassRefPtr<Node> ReplacementFragment::insertFragmentForTestRendering(Node* context)
201 Node* body = m_document->body();
205 RefPtr<StyledElement> holder = static_pointer_cast<StyledElement>(createDefaultParagraphElement(m_document.get()));
207 ExceptionCode ec = 0;
209 // Copy the whitespace style from the context onto this element.
211 while (n && !n->isElementNode())
214 RefPtr<CSSComputedStyleDeclaration> contextStyle = new CSSComputedStyleDeclaration(static_cast<Element*>(n));
215 CSSStyleDeclaration* style = holder->style();
216 style->setProperty(CSS_PROP_WHITE_SPACE, contextStyle->getPropertyValue(CSS_PROP_WHITE_SPACE), false, ec);
220 holder->appendChild(m_fragment, ec);
223 body->appendChild(holder.get(), ec);
226 m_document->updateLayoutIgnorePendingStylesheets();
228 return holder.release();
231 void ReplacementFragment::restoreTestRenderingNodesToFragment(Node *holder)
236 ExceptionCode ec = 0;
237 while (RefPtr<Node> node = holder->firstChild()) {
238 holder->removeChild(node.get(), ec);
240 m_fragment->appendChild(node.get(), ec);
245 void ReplacementFragment::removeUnrenderedNodes(Node *holder)
247 DeprecatedPtrList<Node> unrendered;
249 for (Node *node = holder->firstChild(); node; node = node->traverseNextNode(holder)) {
250 if (!isNodeRendered(node) && !isTableStructureNode(node))
251 unrendered.append(node);
254 for (DeprecatedPtrListIterator<Node> it(unrendered); it.current(); ++it)
255 removeNode(it.current());
258 ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment,
259 bool selectReplacement, bool smartReplace, bool matchStyle, bool preventNesting,
260 EditAction editAction)
261 : CompositeEditCommand(document),
262 m_selectReplacement(selectReplacement),
263 m_smartReplace(smartReplace),
264 m_matchStyle(matchStyle),
265 m_documentFragment(fragment),
266 m_preventNesting(preventNesting),
267 m_editAction(editAction)
271 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart)
273 VisiblePosition startOfInsertedContent(Position(m_firstNodeInserted.get(), 0));
274 VisiblePosition prev = startOfInsertedContent.previous(true);
278 return !selectionStartWasStartOfParagraph &&
279 !fragmentHasInterchangeNewlineAtStart &&
280 isStartOfParagraph(startOfInsertedContent) &&
281 !startOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
282 shouldMerge(startOfInsertedContent, prev);
285 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
287 VisiblePosition endOfInsertedContent(Position(m_lastNodeInserted.get(), maxDeepOffset(m_lastNodeInserted.get())));
288 VisiblePosition next = endOfInsertedContent.next(true);
292 return !selectionEndWasEndOfParagraph &&
293 isEndOfParagraph(endOfInsertedContent) &&
294 !endOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
295 shouldMerge(endOfInsertedContent, next);
298 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& from, const VisiblePosition& to)
300 if (from.isNull() || to.isNull())
303 Node* fromNode = from.deepEquivalent().node();
304 Node* toNode = to.deepEquivalent().node();
306 return nearestMailBlockquote(fromNode) == nearestMailBlockquote(toNode) &&
307 !enclosingBlock(fromNode)->hasTagName(blockquoteTag) &&
308 enclosingListChild(fromNode) == enclosingListChild(toNode) &&
309 enclosingTableCell(fromNode) == enclosingTableCell(toNode) &&
310 !(fromNode->renderer() && fromNode->renderer()->isTable()) &&
311 !(toNode->renderer() && toNode->renderer()->isTable()) &&
312 !fromNode->hasTagName(hrTag) && !toNode->hasTagName(hrTag);
315 void ReplaceSelectionCommand::removeRedundantStyles()
317 typedef HashMap<Node*, RefPtr<CSSMutableStyleDeclaration> > NodeStyleMap;
319 Node* node = m_firstNodeInserted.get();
321 // There's usually a top level style span that holds the document's default style, push it down.
322 if (isStyleSpan(node)) {
324 RefPtr<CSSMutableStyleDeclaration> parentStyle = Position(node, 0).computedStyle()->copyInheritableProperties();
326 RefPtr<Node> child = node->firstChild();
328 Node* next = child->nextSibling();
329 if (isStyleSpan(child.get())) {
330 HTMLElement* elem = static_cast<HTMLElement*>(child.get());
331 CSSMutableStyleDeclaration* inlineStyleDecl = elem->inlineStyleDecl();
332 inlineStyleDecl->merge(parentStyle.get(), false);
333 setNodeAttribute(elem, styleAttr, inlineStyleDecl->cssText());
334 } else if (node->isElementNode()) {
335 RefPtr<Node> clone = node->cloneNode(false);
336 int index = child->nodeIndex();
337 removeNode(child.get());
338 insertNodeAt(clone.get(), node, index);
339 appendNode(child.get(), clone.get());
344 if (m_firstNodeInserted == node)
345 m_firstNodeInserted = node->firstChild();
346 if (m_lastNodeInserted == node)
347 m_lastNodeInserted = node->lastChild();
348 removeNodePreservingChildren(node);
351 node = m_firstNodeInserted.get();
353 // Compute and save the non-redundant styles for all Elements. Don't do any mutation here, because
354 // that would cause the diffs to trigger layouts.
357 Node* next = node->traverseNextNode();
359 if (!node->isHTMLElement()) {
364 RefPtr<CSSMutableStyleDeclaration> style = Position(node, 0).computedStyle()->copyInheritableProperties();
365 RefPtr<CSSMutableStyleDeclaration> parentStyle = Position(node->parentNode(), 0).computedStyle()->copyInheritableProperties();
367 parentStyle->diff(style.get());
368 map.add(node, style);
370 if (node == m_lastNodeInserted.get())
376 NodeStyleMap::const_iterator e = map.end();
377 for (NodeStyleMap::const_iterator it = map.begin(); it != e; ++it) {
378 Node *node = it->first;
380 // Remove empty style spans.
381 if (isStyleSpan(node) && !node->firstChild()) {
382 removeNodeAndPruneAncestors(node);
386 RefPtr<CSSMutableStyleDeclaration> style = it->second;
387 if (style->length() == 0) {
388 // Remove redundant style tags and style spans.
389 if (isStyleSpan(node) ||
390 node->hasTagName(bTag) ||
391 node->hasTagName(fontTag) ||
392 node->hasTagName(iTag) ||
393 node->hasTagName(uTag)) {
394 if (node == m_firstNodeInserted.get())
395 m_firstNodeInserted = node->traverseNextNode();
396 if (node == m_lastNodeInserted.get())
397 m_lastNodeInserted = node->traverseNextNode();
398 removeNodePreservingChildren(node);
403 // Clear redundant styles from elements.
404 HTMLElement* elem = static_cast<HTMLElement*>(node);
405 CSSMutableStyleDeclaration* inlineStyleDecl = elem->inlineStyleDecl();
406 if (inlineStyleDecl) {
407 inlineStyleDecl->removeInheritableProperties();
408 inlineStyleDecl->merge(style.get(), true);
409 setNodeAttribute(elem, styleAttr, inlineStyleDecl->cssText());
414 void ReplaceSelectionCommand::doApply()
416 Selection selection = endingSelection();
417 ASSERT(selection.isCaretOrRange());
418 ASSERT(selection.start().node());
419 if (selection.isNone() || !selection.start().node())
422 if (!selection.isContentRichlyEditable())
425 Element* currentRoot = selection.rootEditableElement();
426 ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
428 if (fragment.isEmpty())
432 m_insertionStyle = styleAtPosition(selection.start());
434 VisiblePosition visibleStart = selection.visibleStart();
435 VisiblePosition visibleEnd = selection.visibleEnd();
437 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
438 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
440 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().node());
442 if (selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph ||
443 startBlock == currentRoot ||
444 startBlock->renderer() && startBlock->renderer()->isListItem())
445 m_preventNesting = false;
447 Position insertionPos = selection.start();
449 if (selection.isRange()) {
450 // When the end of the selection being pasted into is at the end of a paragraph, and that selection
451 // spans multiple blocks, not merging may leave an empty line.
452 // When the start of the selection being pasted into is at the start of a block, not merging
453 // will leave hanging block(s).
454 bool mergeBlocksAfterDelete = isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
455 deleteSelection(false, mergeBlocksAfterDelete, true);
456 visibleStart = endingSelection().visibleStart();
457 if (fragment.hasInterchangeNewlineAtStart()) {
458 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
459 if (!isEndOfDocument(visibleStart))
460 setEndingSelection(visibleStart.next());
462 insertParagraphSeparator();
464 insertionPos = endingSelection().start();
466 ASSERT(selection.isCaret());
467 if (fragment.hasInterchangeNewlineAtStart()) {
468 VisiblePosition next = visibleStart.next(true);
469 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
470 setEndingSelection(next);
472 insertParagraphSeparator();
474 // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
475 // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
476 // As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
477 // not <div>xbar<div>bar</div><div>bazx</div></div>
478 if (m_preventNesting && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
479 insertParagraphSeparator();
480 setEndingSelection(endingSelection().visibleStart().previous());
482 insertionPos = endingSelection().start();
485 // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
486 // p that maps to the same visible position as p (since in the case where a br is at the end of a block and collapsed
487 // away, there are positions after the br which map to the same visible position as [br, 0]).
488 Node* endBR = insertionPos.downstream().node()->hasTagName(brTag) ? insertionPos.downstream().node() : 0;
490 startBlock = enclosingBlock(insertionPos.node());
492 // Adjust insertionPos to prevent nesting.
493 if (m_preventNesting) {
494 ASSERT(startBlock != currentRoot);
495 VisiblePosition visibleInsertionPos(insertionPos);
496 if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
497 insertionPos = positionAfterNode(startBlock);
498 else if (isStartOfBlock(visibleInsertionPos))
499 insertionPos = positionBeforeNode(startBlock);
502 // Paste into run of tabs splits the tab span.
503 insertionPos = positionOutsideTabSpan(insertionPos);
505 // Paste at start or end of link goes outside of link.
506 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
508 Frame *frame = document()->frame();
510 // FIXME: Improve typing style.
511 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
512 frame->clearTypingStyle();
515 // We're finished if there is nothing to add.
516 if (!fragment.firstChild())
519 // 1) Insert the content.
520 // 2) Restore the styles of inserted nodes (since styles were removed during the test insertion).
521 // 3) Merge the start of the added content with the content before the position being pasted into.
522 // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
523 // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
524 // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
525 // incoming fragment.
526 // 5) Add spaces for smart replace.
527 // 6) Select the replacement if requested, and match style if requested.
529 VisiblePosition startOfInsertedContent, endOfInsertedContent;
531 RefPtr<Node> refNode = fragment.firstChild();
532 RefPtr<Node> node = refNode->nextSibling();
534 fragment.removeNode(refNode);
535 insertNodeAtAndUpdateNodesInserted(refNode.get(), insertionPos.node(), insertionPos.offset());
538 Node* next = node->nextSibling();
539 fragment.removeNode(node);
540 insertNodeAfterAndUpdateNodesInserted(node.get(), refNode.get());
545 removeRedundantStyles();
547 endOfInsertedContent = VisiblePosition(Position(m_lastNodeInserted.get(), maxDeepOffset(m_lastNodeInserted.get())));
548 startOfInsertedContent = VisiblePosition(Position(m_firstNodeInserted.get(), 0));
550 // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and
551 // didn't have a br after it, so the inserted content ended up in the same paragraph.
552 if (insertionPos.node() == startBlock->parentNode() && (unsigned)insertionPos.offset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
553 insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent().node(), startOfInsertedContent.deepEquivalent().offset());
555 Position lastPositionToSelect;
557 bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd();
559 if (shouldRemoveEndBR(endBR)) {
560 if (interchangeNewlineAtEnd) {
561 interchangeNewlineAtEnd = false;
562 m_lastNodeInserted = endBR;
563 lastPositionToSelect = VisiblePosition(Position(m_lastNodeInserted.get(), 0)).deepEquivalent();
565 removeNodeAndPruneAncestors(endBR);
568 if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart())) {
569 VisiblePosition destination = startOfInsertedContent.previous();
570 VisiblePosition startOfParagraphToMove = startOfInsertedContent;
572 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
573 // only ever used to create positions where inserted content starts/ends.
574 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
575 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().downstream().node();
576 if (!m_lastNodeInserted->inDocument())
577 m_lastNodeInserted = endingSelection().visibleEnd().deepEquivalent().downstream().node();
580 endOfInsertedContent = VisiblePosition(Position(m_lastNodeInserted.get(), maxDeepOffset(m_lastNodeInserted.get())));
581 startOfInsertedContent = VisiblePosition(Position(m_firstNodeInserted.get(), 0));
583 if (interchangeNewlineAtEnd) {
584 VisiblePosition next = endOfInsertedContent.next(true);
586 if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
587 if (!isStartOfParagraph(endOfInsertedContent)) {
588 setEndingSelection(endOfInsertedContent);
589 insertParagraphSeparator();
591 // Select up to the paragraph separator that was added.
592 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
593 updateNodesInserted(lastPositionToSelect.node());
596 // Select up to the beginning of the next paragraph.
597 lastPositionToSelect = next.deepEquivalent().downstream();
600 } else if (m_lastNodeInserted->hasTagName(brTag)) {
601 // We want to honor the last incoming line break, so, if it will collapse away because of quirks mode,
603 // FIXME: This will expand a br inside a block: <div><br></div>
604 // FIXME: Should we expand all incoming brs that collapse because of quirks mode?
605 if (!document()->inStrictMode() && isEndOfBlock(endOfInsertedContent) && !isStartOfParagraph(endOfInsertedContent))
606 insertNodeBeforeAndUpdateNodesInserted(createBreakElement(document()).get(), m_lastNodeInserted.get());
608 } else if (shouldMergeEnd(selectionEndWasEndOfParagraph)) {
610 // Merging two paragraphs will destroy the moved one's block styles. Always move forward to preserve
611 // the block style of the paragraph already in the document, unless the paragraph to move would include the
612 // what was the start of the selection that was pasted into.
613 bool mergeForward = !inSameParagraph(startOfInsertedContent, endOfInsertedContent) || isStartOfParagraph(startOfInsertedContent);
615 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
616 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
618 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
619 // Merging forward will remove m_lastNodeInserted from the document.
620 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
621 // only ever used to create positions where inserted content starts/ends.
623 m_lastNodeInserted = destination.previous().deepEquivalent().node();
624 if (!m_firstNodeInserted->inDocument())
625 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().node();
629 endOfInsertedContent = VisiblePosition(Position(m_lastNodeInserted.get(), maxDeepOffset(m_lastNodeInserted.get())));
630 startOfInsertedContent = VisiblePosition(Position(m_firstNodeInserted.get(), 0));
632 // Add spaces for smart replace.
633 if (m_smartReplace) {
634 bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) &&
635 !frame->isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false);
636 if (needsTrailingSpace) {
637 RenderObject* renderer = m_lastNodeInserted->renderer();
638 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
639 if (m_lastNodeInserted->isTextNode()) {
640 Text* text = static_cast<Text*>(m_lastNodeInserted.get());
641 insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " ");
643 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
644 insertNodeAfterAndUpdateNodesInserted(node.get(), m_lastNodeInserted.get());
648 bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) &&
649 !frame->isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true);
650 if (needsLeadingSpace) {
651 RenderObject* renderer = m_lastNodeInserted->renderer();
652 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
653 if (m_firstNodeInserted->isTextNode()) {
654 Text* text = static_cast<Text*>(m_firstNodeInserted.get());
655 insertTextIntoNode(text, 0, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
657 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
658 // Don't updateNodesInserted. Doing so would set m_lastNodeInserted to be the node containing the
659 // leading space, but m_lastNodeInserted is supposed to mark the end of pasted content.
660 insertNodeBefore(node.get(), m_firstNodeInserted.get());
661 // FIXME: Use positions to track the start/end of inserted content.
662 m_firstNodeInserted = node;
667 completeHTMLReplacement(lastPositionToSelect);
670 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR)
672 if (!endBR || !endBR->inDocument())
675 VisiblePosition visiblePos(Position(endBR, 0));
678 // The br is collapsed away and so is unnecessary.
679 !document()->inStrictMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos) ||
680 // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
681 // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
682 isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos) && !m_lastNodeInserted->hasTagName(brTag);
685 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
690 if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastNodeInserted && m_lastNodeInserted->inDocument()) {
692 Node* lastLeaf = m_lastNodeInserted->lastDescendant();
693 Node* firstLeaf = m_firstNodeInserted->firstDescendant();
695 start = Position(firstLeaf, 0);
696 end = Position(lastLeaf, maxDeepOffset(lastLeaf));
698 // FIXME: Should we treat all spaces in incoming content as having been rendered?
699 rebalanceWhitespaceAt(start);
700 rebalanceWhitespaceAt(end);
703 assert(m_insertionStyle);
704 applyStyle(m_insertionStyle.get(), start, end);
707 if (lastPositionToSelect.isNotNull())
708 end = lastPositionToSelect;
709 } else if (lastPositionToSelect.isNotNull())
710 start = end = lastPositionToSelect;
714 if (m_selectReplacement)
715 setEndingSelection(Selection(start, end, SEL_DEFAULT_AFFINITY));
717 setEndingSelection(Selection(end, SEL_DEFAULT_AFFINITY));
720 EditAction ReplaceSelectionCommand::editingAction() const
725 void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(Node *insertChild, Node *refChild)
727 insertNodeAfter(insertChild, refChild);
728 updateNodesInserted(insertChild);
731 void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(Node *insertChild, Node *refChild, int offset)
733 insertNodeAt(insertChild, refChild, offset);
734 updateNodesInserted(insertChild);
737 void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(Node *insertChild, Node *refChild)
739 insertNodeBefore(insertChild, refChild);
740 updateNodesInserted(insertChild);
743 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
748 if (!m_firstNodeInserted)
749 m_firstNodeInserted = node;
751 if (node == m_lastNodeInserted)
754 m_lastNodeInserted = node->lastDescendant();
757 } // namespace WebCore