2 * Copyright (C) 2005 Apple 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 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 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 "DeleteSelectionCommand.h"
30 #include "DocumentMarkerController.h"
32 #include "EditorClient.h"
35 #include "htmlediting.h"
36 #include "HTMLInputElement.h"
37 #include "HTMLLinkElement.h"
38 #include "HTMLNames.h"
39 #include "HTMLStyleElement.h"
40 #include "HTMLTableElement.h"
41 #include "NodeTraversal.h"
42 #include "RenderTableCell.h"
43 #include "RenderText.h"
45 #include "VisibleUnits.h"
49 using namespace HTMLNames;
51 static bool isTableRow(const Node* node)
53 return node && node->hasTagName(trTag);
56 static bool isTableCellEmpty(Node* cell)
58 ASSERT(isTableCell(cell));
59 return VisiblePosition(firstPositionInNode(cell)) == VisiblePosition(lastPositionInNode(cell));
62 static bool isTableRowEmpty(Node* row)
67 for (Node* child = row->firstChild(); child; child = child->nextSibling())
68 if (isTableCell(child) && !isTableCellEmpty(child))
74 DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
75 : CompositeEditCommand(document)
76 , m_hasSelectionToDelete(false)
77 , m_smartDelete(smartDelete)
78 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
79 , m_needPlaceholder(false)
81 , m_expandForSpecialElements(expandForSpecialElements)
82 , m_pruneStartBlockIfNecessary(false)
83 , m_startsAtEmptyLine(false)
84 , m_sanitizeMarkup(sanitizeMarkup)
88 , m_deleteIntoBlockquoteStyle(0)
92 DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
93 : CompositeEditCommand(selection.start().anchorNode()->document())
94 , m_hasSelectionToDelete(true)
95 , m_smartDelete(smartDelete)
96 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
97 , m_needPlaceholder(false)
99 , m_expandForSpecialElements(expandForSpecialElements)
100 , m_pruneStartBlockIfNecessary(false)
101 , m_startsAtEmptyLine(false)
102 , m_sanitizeMarkup(sanitizeMarkup)
103 , m_selectionToDelete(selection)
107 , m_deleteIntoBlockquoteStyle(0)
111 void DeleteSelectionCommand::initializeStartEnd(Position& start, Position& end)
113 Node* startSpecialContainer = 0;
114 Node* endSpecialContainer = 0;
116 start = m_selectionToDelete.start();
117 end = m_selectionToDelete.end();
119 // For HRs, we'll get a position at (HR,1) when hitting delete from the beginning of the previous line, or (HR,0) when forward deleting,
120 // but in these cases, we want to delete it, so manually expand the selection
121 if (start.deprecatedNode()->hasTagName(hrTag))
122 start = positionBeforeNode(start.deprecatedNode());
123 else if (end.deprecatedNode()->hasTagName(hrTag))
124 end = positionAfterNode(end.deprecatedNode());
126 // FIXME: This is only used so that moveParagraphs can avoid the bugs in special element expansion.
127 if (!m_expandForSpecialElements)
131 startSpecialContainer = 0;
132 endSpecialContainer = 0;
134 Position s = positionBeforeContainingSpecialElement(start, &startSpecialContainer);
135 Position e = positionAfterContainingSpecialElement(end, &endSpecialContainer);
137 if (!startSpecialContainer && !endSpecialContainer)
140 m_mergeBlocksAfterDelete = false;
142 if (VisiblePosition(start) != m_selectionToDelete.visibleStart() || VisiblePosition(end) != m_selectionToDelete.visibleEnd())
145 // If we're going to expand to include the startSpecialContainer, it must be fully selected.
146 if (startSpecialContainer && !endSpecialContainer && comparePositions(positionInParentAfterNode(startSpecialContainer), end) > -1)
149 // If we're going to expand to include the endSpecialContainer, it must be fully selected.
150 if (endSpecialContainer && !startSpecialContainer && comparePositions(start, positionInParentBeforeNode(endSpecialContainer)) > -1)
153 if (startSpecialContainer && startSpecialContainer->isDescendantOf(endSpecialContainer))
154 // Don't adjust the end yet, it is the end of a special element that contains the start
155 // special element (which may or may not be fully selected).
157 else if (endSpecialContainer && endSpecialContainer->isDescendantOf(startSpecialContainer))
158 // Don't adjust the start yet, it is the start of a special element that contains the end
159 // special element (which may or may not be fully selected).
168 void DeleteSelectionCommand::setStartingSelectionOnSmartDelete(const Position& start, const Position& end)
170 VisiblePosition newBase;
171 VisiblePosition newExtent;
172 if (startingSelection().isBaseFirst()) {
179 setStartingSelection(VisibleSelection(newBase, newExtent, startingSelection().isDirectional()));
182 void DeleteSelectionCommand::initializePositionData()
185 initializeStartEnd(start, end);
187 m_upstreamStart = start.upstream();
188 m_downstreamStart = start.downstream();
189 m_upstreamEnd = end.upstream();
190 m_downstreamEnd = end.downstream();
192 m_startRoot = editableRootForPosition(start);
193 m_endRoot = editableRootForPosition(end);
195 m_startTableRow = enclosingNodeOfType(start, &isTableRow);
196 m_endTableRow = enclosingNodeOfType(end, &isTableRow);
198 // Don't move content out of a table cell.
199 // If the cell is non-editable, enclosingNodeOfType won't return it by default, so
200 // tell that function that we don't care if it returns non-editable nodes.
201 Node* startCell = enclosingNodeOfType(m_upstreamStart, &isTableCell, CanCrossEditingBoundary);
202 Node* endCell = enclosingNodeOfType(m_downstreamEnd, &isTableCell, CanCrossEditingBoundary);
203 // FIXME: This isn't right. A borderless table with two rows and a single column would appear as two paragraphs.
204 if (endCell && endCell != startCell)
205 m_mergeBlocksAfterDelete = false;
207 // Usually the start and the end of the selection to delete are pulled together as a result of the deletion.
208 // Sometimes they aren't (like when no merge is requested), so we must choose one position to hold the caret
209 // and receive the placeholder after deletion.
210 VisiblePosition visibleEnd(m_downstreamEnd);
211 if (m_mergeBlocksAfterDelete && !isEndOfParagraph(visibleEnd))
212 m_endingPosition = m_downstreamEnd;
214 m_endingPosition = m_downstreamStart;
216 // We don't want to merge into a block if it will mean changing the quote level of content after deleting
217 // selections that contain a whole number paragraphs plus a line break, since it is unclear to most users
218 // that such a selection actually ends at the start of the next paragraph. This matches TextEdit behavior
219 // for indented paragraphs.
220 // Only apply this rule if the endingSelection is a range selection. If it is a caret, then other operations have created
221 // the selection we're deleting (like the process of creating a selection to delete during a backspace), and the user isn't in the situation described above.
222 if (numEnclosingMailBlockquotes(start) != numEnclosingMailBlockquotes(end)
223 && isStartOfParagraph(visibleEnd) && isStartOfParagraph(VisiblePosition(start))
224 && endingSelection().isRange()) {
225 m_mergeBlocksAfterDelete = false;
226 m_pruneStartBlockIfNecessary = true;
229 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
230 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity());
231 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
235 // skip smart delete if the selection to delete already starts or ends with whitespace
236 Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.affinity()).deepEquivalent();
237 bool skipSmartDelete = pos.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
238 if (!skipSmartDelete)
239 skipSmartDelete = m_downstreamEnd.leadingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
241 // extend selection upstream if there is whitespace there
242 bool hasLeadingWhitespaceBeforeAdjustment = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity(), true).isNotNull();
243 if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
244 VisiblePosition visiblePos = VisiblePosition(m_upstreamStart, VP_DEFAULT_AFFINITY).previous();
245 pos = visiblePos.deepEquivalent();
246 // Expand out one character upstream for smart delete and recalculate
247 // positions based on this change.
248 m_upstreamStart = pos.upstream();
249 m_downstreamStart = pos.downstream();
250 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(visiblePos.affinity());
252 setStartingSelectionOnSmartDelete(m_upstreamStart, m_upstreamEnd);
255 // trailing whitespace is only considered for smart delete if there is no leading
256 // whitespace, as in the case where you double-click the first word of a paragraph.
257 if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull()) {
258 // Expand out one character downstream for smart delete and recalculate
259 // positions based on this change.
260 pos = VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY).next().deepEquivalent();
261 m_upstreamEnd = pos.upstream();
262 m_downstreamEnd = pos.downstream();
263 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
265 setStartingSelectionOnSmartDelete(m_downstreamStart, m_downstreamEnd);
269 // We must pass call parentAnchoredEquivalent on the positions since some editing positions
270 // that appear inside their nodes aren't really inside them. [hr, 0] is one example.
271 // FIXME: parentAnchoredEquivalent should eventually be moved into enclosing element getters
272 // like the one below, since editing functions should obviously accept editing positions.
273 // FIXME: Passing false to enclosingNodeOfType tells it that it's OK to return a non-editable
274 // node. This was done to match existing behavior, but it seems wrong.
275 m_startBlock = enclosingNodeOfType(m_downstreamStart.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
276 m_endBlock = enclosingNodeOfType(m_upstreamEnd.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
279 void DeleteSelectionCommand::saveTypingStyleState()
281 // A common case is deleting characters that are all from the same text node. In
282 // that case, the style at the start of the selection before deletion will be the
283 // same as the style at the start of the selection after deletion (since those
284 // two positions will be identical). Therefore there is no need to save the
285 // typing style at the start of the selection, nor is there a reason to
286 // compute the style at the start of the selection after deletion (see the
287 // early return in calculateTypingStyleAfterDelete).
288 // However, if typing style was previously set from another text node at the previous
289 // position (now deleted), we need to clear that style as well.
290 if (m_upstreamStart.deprecatedNode() == m_downstreamEnd.deprecatedNode() && m_upstreamStart.deprecatedNode()->isTextNode()) {
291 frame().selection().clearTypingStyle();
295 // Figure out the typing style in effect before the delete is done.
296 m_typingStyle = EditingStyle::create(m_selectionToDelete.start(), EditingStyle::EditingPropertiesInEffect);
297 m_typingStyle->removeStyleAddedByNode(enclosingAnchorElement(m_selectionToDelete.start()));
299 // If we're deleting into a Mail blockquote, save the style at end() instead of start()
300 // We'll use this later in computeTypingStyleAfterDelete if we end up outside of a Mail blockquote
301 if (enclosingNodeOfType(m_selectionToDelete.start(), isMailBlockquote))
302 m_deleteIntoBlockquoteStyle = EditingStyle::create(m_selectionToDelete.end());
304 m_deleteIntoBlockquoteStyle = 0;
307 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
309 Node* nodeAfterUpstreamStart = m_upstreamStart.computeNodeAfterPosition();
310 Node* nodeAfterDownstreamStart = m_downstreamStart.computeNodeAfterPosition();
311 // Upstream end will appear before BR due to canonicalization
312 Node* nodeAfterUpstreamEnd = m_upstreamEnd.computeNodeAfterPosition();
314 if (!nodeAfterUpstreamStart || !nodeAfterDownstreamStart)
317 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
318 bool upstreamStartIsBR = nodeAfterUpstreamStart->hasTagName(brTag);
319 bool downstreamStartIsBR = nodeAfterDownstreamStart->hasTagName(brTag);
320 // We should consider that the BR is on a line by itself also when we have <br><br>. This test should be true only
321 // when the two elements are siblings and should be false in a case like <div><br></div><br>.
322 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && ((nodeAfterDownstreamStart == nodeAfterUpstreamEnd) || (nodeAfterUpstreamEnd && nodeAfterUpstreamEnd->hasTagName(brTag) && nodeAfterUpstreamStart->nextSibling() == nodeAfterUpstreamEnd));
324 if (isBROnLineByItself) {
325 removeNode(nodeAfterDownstreamStart);
329 // FIXME: This code doesn't belong in here.
330 // We detect the case where the start is an empty line consisting of BR not wrapped in a block element.
331 if (upstreamStartIsBR && downstreamStartIsBR
332 && !(isStartOfBlock(positionBeforeNode(nodeAfterUpstreamStart)) && isEndOfBlock(positionAfterNode(nodeAfterDownstreamStart)))
333 && (!nodeAfterUpstreamEnd || nodeAfterUpstreamEnd->hasTagName(brTag) || nodeAfterUpstreamEnd->previousSibling() != nodeAfterUpstreamStart)) {
334 m_startsAtEmptyLine = true;
335 m_endingPosition = m_downstreamEnd;
341 static Position firstEditablePositionInNode(Node* node)
345 while (next && !next->hasEditableStyle())
346 next = NodeTraversal::next(next, node);
347 return next ? firstPositionInOrBeforeNode(next) : Position();
350 void DeleteSelectionCommand::removeNode(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
355 if (m_startRoot != m_endRoot && !(node->isDescendantOf(m_startRoot.get()) && node->isDescendantOf(m_endRoot.get()))) {
356 // If a node is not in both the start and end editable roots, remove it only if its inside an editable region.
357 if (!node->parentNode()->hasEditableStyle()) {
358 // Don't remove non-editable atomic nodes.
359 if (!node->firstChild())
361 // Search this non-editable region for editable regions to empty.
362 RefPtr<Node> child = node->firstChild();
364 RefPtr<Node> nextChild = child->nextSibling();
365 removeNode(child.get(), shouldAssumeContentIsAlwaysEditable);
366 // Bail if nextChild is no longer node's child.
367 if (nextChild && nextChild->parentNode() != node)
372 // Don't remove editable regions that are inside non-editable ones, just clear them.
377 if (isTableStructureNode(node.get()) || node->isRootEditableElement()) {
378 // Do not remove an element of table structure; remove its contents.
379 // Likewise for the root editable element.
380 Node* child = node->firstChild();
382 Node* remove = child;
383 child = child->nextSibling();
384 removeNode(remove, shouldAssumeContentIsAlwaysEditable);
387 // Make sure empty cell has some height, if a placeholder can be inserted.
388 document().updateLayoutIgnorePendingStylesheets();
389 RenderObject* renderer = node->renderer();
390 if (is<RenderTableCell>(renderer) && downcast<RenderTableCell>(*renderer).contentHeight() <= 0) {
391 Position firstEditablePosition = firstEditablePositionInNode(node.get());
392 if (firstEditablePosition.isNotNull())
393 insertBlockPlaceholder(firstEditablePosition);
398 if (node == m_startBlock && !isEndOfBlock(VisiblePosition(firstPositionInNode(m_startBlock.get())).previous()))
399 m_needPlaceholder = true;
400 else if (node == m_endBlock && !isStartOfBlock(VisiblePosition(lastPositionInNode(m_startBlock.get())).next()))
401 m_needPlaceholder = true;
403 // FIXME: Update the endpoints of the range being deleted.
404 updatePositionForNodeRemoval(m_endingPosition, node.get());
405 updatePositionForNodeRemoval(m_leadingWhitespace, node.get());
406 updatePositionForNodeRemoval(m_trailingWhitespace, node.get());
408 CompositeEditCommand::removeNode(node, shouldAssumeContentIsAlwaysEditable);
411 static void updatePositionForTextRemoval(Node* node, int offset, int count, Position& position)
413 if (position.anchorType() != Position::PositionIsOffsetInAnchor || position.containerNode() != node)
416 if (position.offsetInContainerNode() > offset + count)
417 position.moveToOffset(position.offsetInContainerNode() - count);
418 else if (position.offsetInContainerNode() > offset)
419 position.moveToOffset(offset);
422 void DeleteSelectionCommand::deleteTextFromNode(PassRefPtr<Text> node, unsigned offset, unsigned count)
424 // FIXME: Update the endpoints of the range being deleted.
425 updatePositionForTextRemoval(node.get(), offset, count, m_endingPosition);
426 updatePositionForTextRemoval(node.get(), offset, count, m_leadingWhitespace);
427 updatePositionForTextRemoval(node.get(), offset, count, m_trailingWhitespace);
428 updatePositionForTextRemoval(node.get(), offset, count, m_downstreamEnd);
430 CompositeEditCommand::deleteTextFromNode(node, offset, count);
433 void DeleteSelectionCommand::makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss()
435 RefPtr<Range> range = m_selectionToDelete.toNormalizedRange();
436 RefPtr<Node> node = range->firstNode();
437 while (node && node != range->pastLastNode()) {
438 RefPtr<Node> nextNode = NodeTraversal::next(node.get());
439 if ((is<HTMLStyleElement>(*node) && !downcast<HTMLStyleElement>(*node).hasAttribute(scopedAttr)) || is<HTMLLinkElement>(*node)) {
440 nextNode = NodeTraversal::nextSkippingChildren(node.get());
441 RefPtr<ContainerNode> rootEditableElement = node->rootEditableElement();
442 if (rootEditableElement) {
444 appendNode(node, rootEditableElement);
451 void DeleteSelectionCommand::handleGeneralDelete()
453 if (m_upstreamStart.isNull())
456 int startOffset = m_upstreamStart.deprecatedEditingOffset();
457 Node* startNode = m_upstreamStart.deprecatedNode();
459 makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
461 // Never remove the start block unless it's a table, in which case we won't merge content in.
462 if (startNode == m_startBlock && !startOffset && canHaveChildrenForEditing(startNode) && !is<HTMLTableElement>(*startNode)) {
464 startNode = NodeTraversal::next(startNode);
469 if (startOffset >= caretMaxOffset(startNode) && is<Text>(*startNode)) {
470 Text& text = downcast<Text>(*startNode);
471 if (text.length() > static_cast<unsigned>(caretMaxOffset(startNode)))
472 deleteTextFromNode(&text, caretMaxOffset(startNode), text.length() - caretMaxOffset(startNode));
475 if (startOffset >= lastOffsetForEditing(startNode)) {
476 startNode = NodeTraversal::nextSkippingChildren(startNode);
480 // Done adjusting the start. See if we're all done.
484 if (startNode == m_downstreamEnd.deprecatedNode()) {
485 if (m_downstreamEnd.deprecatedEditingOffset() - startOffset > 0) {
486 if (is<Text>(*startNode)) {
487 // in a text node that needs to be trimmed
488 Text& text = downcast<Text>(*startNode);
489 deleteTextFromNode(&text, startOffset, m_downstreamEnd.deprecatedEditingOffset() - startOffset);
491 removeChildrenInRange(startNode, startOffset, m_downstreamEnd.deprecatedEditingOffset());
492 m_endingPosition = m_upstreamStart;
496 // The selection to delete is all in one node.
497 if (!startNode->renderer() || (!startOffset && m_downstreamEnd.atLastEditingPositionForNode()))
498 removeNode(startNode);
501 bool startNodeWasDescendantOfEndNode = m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode());
502 // The selection to delete spans more than one node.
503 RefPtr<Node> node(startNode);
505 if (startOffset > 0) {
506 if (is<Text>(*startNode)) {
507 // in a text node that needs to be trimmed
508 Text& text = downcast<Text>(*node);
509 deleteTextFromNode(&text, startOffset, text.length() - startOffset);
510 node = NodeTraversal::next(node.get());
512 node = startNode->traverseToChildAt(startOffset);
514 } else if (startNode == m_upstreamEnd.deprecatedNode() && is<Text>(*startNode)) {
515 Text& text = downcast<Text>(*m_upstreamEnd.deprecatedNode());
516 deleteTextFromNode(&text, 0, m_upstreamEnd.deprecatedEditingOffset());
519 // handle deleting all nodes that are completely selected
520 while (node && node != m_downstreamEnd.deprecatedNode()) {
521 if (comparePositions(firstPositionInOrBeforeNode(node.get()), m_downstreamEnd) >= 0) {
522 // NodeTraversal::nextSkippingChildren just blew past the end position, so stop deleting
524 } else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
525 RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(node.get());
526 // if we just removed a node from the end container, update end position so the
527 // check above will work
528 updatePositionForNodeRemoval(m_downstreamEnd, node.get());
529 removeNode(node.get());
530 node = nextNode.get();
532 Node* n = node->lastDescendant();
533 if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(n)) {
534 removeNode(node.get());
537 node = NodeTraversal::next(node.get());
541 if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.anchorNode()->inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
542 if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.deprecatedNode())) {
543 // The node itself is fully selected, not just its contents. Delete it.
544 removeNode(m_downstreamEnd.deprecatedNode());
546 if (is<Text>(*m_downstreamEnd.deprecatedNode())) {
547 // in a text node that needs to be trimmed
548 Text& text = downcast<Text>(*m_downstreamEnd.deprecatedNode());
549 if (m_downstreamEnd.deprecatedEditingOffset() > 0) {
550 deleteTextFromNode(&text, 0, m_downstreamEnd.deprecatedEditingOffset());
552 // Remove children of m_downstreamEnd.deprecatedNode() that come after m_upstreamStart.
553 // Don't try to remove children if m_upstreamStart was inside m_downstreamEnd.deprecatedNode()
554 // and m_upstreamStart has been removed from the document, because then we don't
555 // know how many children to remove.
556 // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
557 // always know which children to remove.
558 } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.anchorNode()->inDocument())) {
560 if (m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode())) {
561 Node* n = m_upstreamStart.deprecatedNode();
562 while (n && n->parentNode() != m_downstreamEnd.deprecatedNode())
565 offset = n->computeNodeIndex() + 1;
567 removeChildrenInRange(m_downstreamEnd.deprecatedNode(), offset, m_downstreamEnd.deprecatedEditingOffset());
568 m_downstreamEnd = createLegacyEditingPosition(m_downstreamEnd.deprecatedNode(), offset);
575 void DeleteSelectionCommand::fixupWhitespace()
577 document().updateLayoutIgnorePendingStylesheets();
578 // FIXME: isRenderedCharacter should be removed, and we should use VisiblePosition::characterAfter and VisiblePosition::characterBefore
579 if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharacter() && is<Text>(*m_leadingWhitespace.deprecatedNode())) {
580 Text& textNode = downcast<Text>(*m_leadingWhitespace.deprecatedNode());
581 ASSERT(!textNode.renderer() || textNode.renderer()->style().collapseWhiteSpace());
582 replaceTextInNodePreservingMarkers(&textNode, m_leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
584 if (m_trailingWhitespace.isNotNull() && !m_trailingWhitespace.isRenderedCharacter() && is<Text>(*m_trailingWhitespace.deprecatedNode())) {
585 Text& textNode = downcast<Text>(*m_trailingWhitespace.deprecatedNode());
586 ASSERT(!textNode.renderer() || textNode.renderer()->style().collapseWhiteSpace());
587 replaceTextInNodePreservingMarkers(&textNode, m_trailingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
591 // If a selection starts in one block and ends in another, we have to merge to bring content before the
592 // start together with content after the end.
593 void DeleteSelectionCommand::mergeParagraphs()
595 if (!m_mergeBlocksAfterDelete) {
596 if (m_pruneStartBlockIfNecessary) {
597 // We aren't going to merge into the start block, so remove it if it's empty.
599 // Removing the start block during a deletion is usually an indication that we need
600 // a placeholder, but not in this case.
601 m_needPlaceholder = false;
606 // It shouldn't have been asked to both try and merge content into the start block and prune it.
607 ASSERT(!m_pruneStartBlockIfNecessary);
609 // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
610 if (!m_downstreamEnd.anchorNode()->inDocument() || !m_upstreamStart.anchorNode()->inDocument())
613 // FIXME: The deletion algorithm shouldn't let this happen.
614 if (comparePositions(m_upstreamStart, m_downstreamEnd) > 0)
617 // There's nothing to merge.
618 if (m_upstreamStart == m_downstreamEnd)
621 VisiblePosition startOfParagraphToMove(m_downstreamEnd);
622 VisiblePosition mergeDestination(m_upstreamStart);
624 // m_downstreamEnd's block has been emptied out by deletion. There is no content inside of it to
625 // move, so just remove it.
626 Element* endBlock = enclosingBlock(m_downstreamEnd.deprecatedNode());
627 if (!endBlock || !endBlock->contains(startOfParagraphToMove.deepEquivalent().deprecatedNode()) || !startOfParagraphToMove.deepEquivalent().deprecatedNode()) {
628 removeNode(enclosingBlock(m_downstreamEnd.deprecatedNode()));
632 // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
633 if (!mergeDestination.deepEquivalent().deprecatedNode() || !mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) || m_startsAtEmptyLine) {
634 insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
635 mergeDestination = VisiblePosition(m_upstreamStart);
638 if (mergeDestination == startOfParagraphToMove)
641 VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove, CanSkipOverEditingBoundary);
643 if (mergeDestination == endOfParagraphToMove)
646 // The rule for merging into an empty block is: only do so if its farther to the right.
647 // FIXME: Consider RTL.
648 if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfParagraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds().x()) {
649 if (mergeDestination.deepEquivalent().downstream().deprecatedNode()->hasTagName(brTag)) {
650 removeNodeAndPruneAncestors(mergeDestination.deepEquivalent().downstream().deprecatedNode());
651 m_endingPosition = startOfParagraphToMove.deepEquivalent();
656 // Block images, tables and horizontal rules cannot be made inline with content at mergeDestination. If there is
657 // any (!isStartOfParagraph(mergeDestination)), don't merge, just move the caret to just before the selection we deleted.
658 // See https://bugs.webkit.org/show_bug.cgi?id=25439
659 if (isRenderedAsNonInlineTableImageOrHR(startOfParagraphToMove.deepEquivalent().deprecatedNode()) && !isStartOfParagraph(mergeDestination)) {
660 m_endingPosition = m_upstreamStart;
664 RefPtr<Range> range = Range::create(document(), startOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent(), endOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent());
665 RefPtr<Range> rangeToBeReplaced = Range::create(document(), mergeDestination.deepEquivalent().parentAnchoredEquivalent(), mergeDestination.deepEquivalent().parentAnchoredEquivalent());
666 if (!frame().editor().client()->shouldMoveRangeAfterDelete(range.get(), rangeToBeReplaced.get()))
669 // moveParagraphs will insert placeholders if it removes blocks that would require their use, don't let block
670 // removals that it does cause the insertion of *another* placeholder.
671 bool needPlaceholder = m_needPlaceholder;
672 bool paragraphToMergeIsEmpty = (startOfParagraphToMove == endOfParagraphToMove);
673 moveParagraph(startOfParagraphToMove, endOfParagraphToMove, mergeDestination, false, !paragraphToMergeIsEmpty);
674 m_needPlaceholder = needPlaceholder;
675 // The endingPosition was likely clobbered by the move, so recompute it (moveParagraph selects the moved paragraph).
676 m_endingPosition = endingSelection().start();
679 void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows()
681 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
682 Node* row = m_endTableRow->previousSibling();
683 while (row && row != m_startTableRow) {
684 RefPtr<Node> previousRow = row->previousSibling();
685 if (isTableRowEmpty(row))
686 // Use a raw removeNode, instead of DeleteSelectionCommand's, because
687 // that won't remove rows, it only empties them in preparation for this function.
688 CompositeEditCommand::removeNode(row);
689 row = previousRow.get();
693 // Remove empty rows after the start row.
694 if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m_endTableRow) {
695 Node* row = m_startTableRow->nextSibling();
696 while (row && row != m_endTableRow) {
697 RefPtr<Node> nextRow = row->nextSibling();
698 if (isTableRowEmpty(row))
699 CompositeEditCommand::removeNode(row);
704 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow)
705 if (isTableRowEmpty(m_endTableRow.get())) {
706 // Don't remove m_endTableRow if it's where we're putting the ending selection.
707 if (!m_endingPosition.deprecatedNode()->isDescendantOf(m_endTableRow.get())) {
708 // FIXME: We probably shouldn't remove m_endTableRow unless it's fully selected, even if it is empty.
709 // We'll need to start adjusting the selection endpoints during deletion to know whether or not m_endTableRow
710 // was fully selected here.
711 CompositeEditCommand::removeNode(m_endTableRow.get());
716 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
721 // Compute the difference between the style before the delete and the style now
722 // after the delete has been done. Set this style on the frame, so other editing
723 // commands being composed with this one will work, and also cache it on the command,
724 // so the Frame::appliedEditing can set it after the whole composite command
727 // If we deleted into a blockquote, but are now no longer in a blockquote, use the alternate typing style
728 if (m_deleteIntoBlockquoteStyle && !enclosingNodeOfType(m_endingPosition, isMailBlockquote, CanCrossEditingBoundary))
729 m_typingStyle = m_deleteIntoBlockquoteStyle;
730 m_deleteIntoBlockquoteStyle = 0;
732 m_typingStyle->prepareToApplyAt(m_endingPosition);
733 if (m_typingStyle->isEmpty())
735 // This is where we've deleted all traces of a style but not a whole paragraph (that's handled above).
736 // In this case if we start typing, the new characters should have the same style as the just deleted ones,
737 // but, if we change the selection, come back and start typing that style should be lost. Also see
738 // preserveTypingStyle() below.
739 frame().selection().setTypingStyle(m_typingStyle);
742 void DeleteSelectionCommand::clearTransientState()
744 m_selectionToDelete = VisibleSelection();
745 m_upstreamStart.clear();
746 m_downstreamStart.clear();
747 m_upstreamEnd.clear();
748 m_downstreamEnd.clear();
749 m_endingPosition.clear();
750 m_leadingWhitespace.clear();
751 m_trailingWhitespace.clear();
754 String DeleteSelectionCommand::originalStringForAutocorrectionAtBeginningOfSelection()
756 if (!m_selectionToDelete.isRange())
759 VisiblePosition startOfSelection = m_selectionToDelete.start();
760 if (!isStartOfWord(startOfSelection))
763 VisiblePosition nextPosition = startOfSelection.next();
764 if (nextPosition.isNull())
767 RefPtr<Range> rangeOfFirstCharacter = Range::create(document(), startOfSelection.deepEquivalent(), nextPosition.deepEquivalent());
768 Vector<DocumentMarker*> markers = document().markers().markersInRange(rangeOfFirstCharacter.get(), DocumentMarker::Autocorrected);
769 for (size_t i = 0; i < markers.size(); ++i) {
770 const DocumentMarker* marker = markers[i];
771 int startOffset = marker->startOffset();
772 if (startOffset == startOfSelection.deepEquivalent().offsetInContainerNode())
773 return marker->description();
778 // This method removes div elements with no attributes that have only one child or no children at all.
779 void DeleteSelectionCommand::removeRedundantBlocks()
781 Node* node = m_endingPosition.containerNode();
782 Node* rootNode = node->rootEditableElement();
784 while (node != rootNode) {
785 if (isRemovableBlock(node)) {
786 if (node == m_endingPosition.anchorNode())
787 updatePositionForNodeRemovalPreservingChildren(m_endingPosition, node);
789 CompositeEditCommand::removeNodePreservingChildren(node);
790 node = m_endingPosition.anchorNode();
792 node = node->parentNode();
796 void DeleteSelectionCommand::doApply()
798 // If selection has not been set to a custom selection when the command was created,
799 // use the current ending selection.
800 if (!m_hasSelectionToDelete)
801 m_selectionToDelete = endingSelection();
803 if (!m_selectionToDelete.isNonOrphanedRange())
806 String originalString = originalStringForAutocorrectionAtBeginningOfSelection();
808 // If the deletion is occurring in a text field, and we're not deleting to replace the selection, then let the frame call across the bridge to notify the form delegate.
810 Element* textControl = enclosingTextFormControl(m_selectionToDelete.start());
811 if (textControl && textControl->focused())
812 frame().editor().textWillBeDeletedInTextField(textControl);
815 // save this to later make the selection with
816 EAffinity affinity = m_selectionToDelete.affinity();
818 Position downstreamEnd = m_selectionToDelete.end().downstream();
819 m_needPlaceholder = isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditingBoundary)
820 && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBoundary)
821 && !lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
822 if (m_needPlaceholder) {
823 // Don't need a placeholder when deleting a selection that starts just before a table
824 // and ends inside it (we do need placeholders to hold open empty cells, but that's
825 // handled elsewhere).
826 if (Node* table = isLastPositionBeforeTable(m_selectionToDelete.visibleStart()))
827 if (m_selectionToDelete.end().deprecatedNode()->isDescendantOf(table))
828 m_needPlaceholder = false;
833 initializePositionData();
835 // Delete any text that may hinder our ability to fixup whitespace after the delete
836 deleteInsignificantTextDownstream(m_trailingWhitespace);
838 saveTypingStyleState();
840 // deleting just a BR is handled specially, at least because we do not
841 // want to replace it with a placeholder BR!
842 if (handleSpecialCaseBRDelete()) {
843 calculateTypingStyleAfterDelete();
844 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
845 clearTransientState();
846 rebalanceWhitespace();
850 handleGeneralDelete();
856 removePreviouslySelectedEmptyTableRows();
858 RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
861 if (m_sanitizeMarkup)
862 removeRedundantBlocks();
863 insertNodeAt(placeholder.get(), m_endingPosition);
866 bool shouldRebalaceWhiteSpace = true;
867 if (!frame().editor().behavior().shouldRebalanceWhiteSpacesInSecureField()) {
868 Node* node = m_endingPosition.deprecatedNode();
869 if (is<Text>(node)) {
870 Text& textNode = downcast<Text>(*node);
871 if (textNode.length())
872 shouldRebalaceWhiteSpace = textNode.renderer()->style().textSecurity() == TSNONE;
875 if (shouldRebalaceWhiteSpace)
876 rebalanceWhitespaceAt(m_endingPosition);
878 calculateTypingStyleAfterDelete();
880 if (!originalString.isEmpty())
881 frame().editor().deletedAutocorrectionAtPosition(m_endingPosition, originalString);
883 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
884 clearTransientState();
887 EditAction DeleteSelectionCommand::editingAction() const
889 // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
890 // but in that case there's a TypingCommand that supplies the editingAction(), so
891 // the Undo menu correctly shows "Undo Typing"
892 return EditActionCut;
895 // Normally deletion doesn't preserve the typing style that was present before it. For example,
896 // type a character, Bold, then delete the character and start typing. The Bold typing style shouldn't
897 // stick around. Deletion should preserve a typing style that *it* sets, however.
898 bool DeleteSelectionCommand::preservesTypingStyle() const
900 return m_typingStyle;
903 } // namespace WebCore