2 * Copyright (C) 2005 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 "DeleteSelectionCommand.h"
30 #include "DocumentFragment.h"
31 #include "DocumentMarkerController.h"
32 #include "EditingBoundary.h"
34 #include "EditorClient.h"
37 #include "htmlediting.h"
38 #include "HTMLInputElement.h"
39 #include "HTMLNames.h"
40 #include "RenderTableCell.h"
42 #include "visible_units.h"
46 using namespace HTMLNames;
48 static bool isTableRow(const Node* node)
50 return node && node->hasTagName(trTag);
53 static bool isTableCellEmpty(Node* cell)
55 ASSERT(isTableCell(cell));
56 return VisiblePosition(firstPositionInNode(cell)) == VisiblePosition(lastPositionInNode(cell));
59 static bool isTableRowEmpty(Node* row)
64 for (Node* child = row->firstChild(); child; child = child->nextSibling())
65 if (isTableCell(child) && !isTableCellEmpty(child))
71 DeleteSelectionCommand::DeleteSelectionCommand(Document *document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
72 : CompositeEditCommand(document)
73 , m_hasSelectionToDelete(false)
74 , m_smartDelete(smartDelete)
75 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
76 , m_needPlaceholder(false)
78 , m_expandForSpecialElements(expandForSpecialElements)
79 , m_pruneStartBlockIfNecessary(false)
80 , m_startsAtEmptyLine(false)
84 , m_deleteIntoBlockquoteStyle(0)
88 DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
89 : CompositeEditCommand(selection.start().anchorNode()->document())
90 , m_hasSelectionToDelete(true)
91 , m_smartDelete(smartDelete)
92 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
93 , m_needPlaceholder(false)
95 , m_expandForSpecialElements(expandForSpecialElements)
96 , m_pruneStartBlockIfNecessary(false)
97 , m_startsAtEmptyLine(false)
98 , m_selectionToDelete(selection)
102 , m_deleteIntoBlockquoteStyle(0)
106 void DeleteSelectionCommand::initializeStartEnd(Position& start, Position& end)
108 Node* startSpecialContainer = 0;
109 Node* endSpecialContainer = 0;
111 start = m_selectionToDelete.start();
112 end = m_selectionToDelete.end();
114 // 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,
115 // but in these cases, we want to delete it, so manually expand the selection
116 if (start.deprecatedNode()->hasTagName(hrTag))
117 start = positionBeforeNode(start.deprecatedNode());
118 else if (end.deprecatedNode()->hasTagName(hrTag))
119 end = positionAfterNode(end.deprecatedNode());
121 // FIXME: This is only used so that moveParagraphs can avoid the bugs in special element expansion.
122 if (!m_expandForSpecialElements)
126 startSpecialContainer = 0;
127 endSpecialContainer = 0;
129 Position s = positionBeforeContainingSpecialElement(start, &startSpecialContainer);
130 Position e = positionAfterContainingSpecialElement(end, &endSpecialContainer);
132 if (!startSpecialContainer && !endSpecialContainer)
135 if (VisiblePosition(start) != m_selectionToDelete.visibleStart() || VisiblePosition(end) != m_selectionToDelete.visibleEnd())
138 // If we're going to expand to include the startSpecialContainer, it must be fully selected.
139 if (startSpecialContainer && !endSpecialContainer && comparePositions(positionInParentAfterNode(startSpecialContainer), end) > -1)
142 // If we're going to expand to include the endSpecialContainer, it must be fully selected.
143 if (endSpecialContainer && !startSpecialContainer && comparePositions(start, positionInParentBeforeNode(endSpecialContainer)) > -1)
146 if (startSpecialContainer && startSpecialContainer->isDescendantOf(endSpecialContainer))
147 // Don't adjust the end yet, it is the end of a special element that contains the start
148 // special element (which may or may not be fully selected).
150 else if (endSpecialContainer && endSpecialContainer->isDescendantOf(startSpecialContainer))
151 // Don't adjust the start yet, it is the start of a special element that contains the end
152 // special element (which may or may not be fully selected).
161 void DeleteSelectionCommand::setStartingSelectionOnSmartDelete(const Position& start, const Position& end)
163 VisiblePosition newBase;
164 VisiblePosition newExtent;
165 if (startingSelection().isBaseFirst()) {
172 setStartingSelection(VisibleSelection(newBase, newExtent, startingSelection().isDirectional()));
175 void DeleteSelectionCommand::initializePositionData()
178 initializeStartEnd(start, end);
180 m_upstreamStart = start.upstream();
181 m_downstreamStart = start.downstream();
182 m_upstreamEnd = end.upstream();
183 m_downstreamEnd = end.downstream();
185 m_startRoot = editableRootForPosition(start);
186 m_endRoot = editableRootForPosition(end);
188 m_startTableRow = enclosingNodeOfType(start, &isTableRow);
189 m_endTableRow = enclosingNodeOfType(end, &isTableRow);
191 // Don't move content out of a table cell.
192 // If the cell is non-editable, enclosingNodeOfType won't return it by default, so
193 // tell that function that we don't care if it returns non-editable nodes.
194 Node* startCell = enclosingNodeOfType(m_upstreamStart, &isTableCell, CanCrossEditingBoundary);
195 Node* endCell = enclosingNodeOfType(m_downstreamEnd, &isTableCell, CanCrossEditingBoundary);
196 // FIXME: This isn't right. A borderless table with two rows and a single column would appear as two paragraphs.
197 if (endCell && endCell != startCell)
198 m_mergeBlocksAfterDelete = false;
200 // Usually the start and the end of the selection to delete are pulled together as a result of the deletion.
201 // Sometimes they aren't (like when no merge is requested), so we must choose one position to hold the caret
202 // and receive the placeholder after deletion.
203 VisiblePosition visibleEnd(m_downstreamEnd);
204 if (m_mergeBlocksAfterDelete && !isEndOfParagraph(visibleEnd))
205 m_endingPosition = m_downstreamEnd;
207 m_endingPosition = m_downstreamStart;
209 // We don't want to merge into a block if it will mean changing the quote level of content after deleting
210 // selections that contain a whole number paragraphs plus a line break, since it is unclear to most users
211 // that such a selection actually ends at the start of the next paragraph. This matches TextEdit behavior
212 // for indented paragraphs.
213 // Only apply this rule if the endingSelection is a range selection. If it is a caret, then other operations have created
214 // 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.
215 if (numEnclosingMailBlockquotes(start) != numEnclosingMailBlockquotes(end)
216 && isStartOfParagraph(visibleEnd) && isStartOfParagraph(VisiblePosition(start))
217 && endingSelection().isRange()) {
218 m_mergeBlocksAfterDelete = false;
219 m_pruneStartBlockIfNecessary = true;
222 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
223 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity());
224 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
228 // skip smart delete if the selection to delete already starts or ends with whitespace
229 Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.affinity()).deepEquivalent();
230 bool skipSmartDelete = pos.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
231 if (!skipSmartDelete)
232 skipSmartDelete = m_downstreamEnd.leadingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
234 // extend selection upstream if there is whitespace there
235 bool hasLeadingWhitespaceBeforeAdjustment = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity(), true).isNotNull();
236 if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
237 VisiblePosition visiblePos = VisiblePosition(m_upstreamStart, VP_DEFAULT_AFFINITY).previous();
238 pos = visiblePos.deepEquivalent();
239 // Expand out one character upstream for smart delete and recalculate
240 // positions based on this change.
241 m_upstreamStart = pos.upstream();
242 m_downstreamStart = pos.downstream();
243 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(visiblePos.affinity());
245 setStartingSelectionOnSmartDelete(m_upstreamStart, m_upstreamEnd);
248 // trailing whitespace is only considered for smart delete if there is no leading
249 // whitespace, as in the case where you double-click the first word of a paragraph.
250 if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull()) {
251 // Expand out one character downstream for smart delete and recalculate
252 // positions based on this change.
253 pos = VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY).next().deepEquivalent();
254 m_upstreamEnd = pos.upstream();
255 m_downstreamEnd = pos.downstream();
256 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
258 setStartingSelectionOnSmartDelete(m_downstreamStart, m_downstreamEnd);
262 // We must pass call parentAnchoredEquivalent on the positions since some editing positions
263 // that appear inside their nodes aren't really inside them. [hr, 0] is one example.
264 // FIXME: parentAnchoredEquivalent should eventually be moved into enclosing element getters
265 // like the one below, since editing functions should obviously accept editing positions.
266 // FIXME: Passing false to enclosingNodeOfType tells it that it's OK to return a non-editable
267 // node. This was done to match existing behavior, but it seems wrong.
268 m_startBlock = enclosingNodeOfType(m_downstreamStart.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
269 m_endBlock = enclosingNodeOfType(m_upstreamEnd.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
272 void DeleteSelectionCommand::saveTypingStyleState()
274 // A common case is deleting characters that are all from the same text node. In
275 // that case, the style at the start of the selection before deletion will be the
276 // same as the style at the start of the selection after deletion (since those
277 // two positions will be identical). Therefore there is no need to save the
278 // typing style at the start of the selection, nor is there a reason to
279 // compute the style at the start of the selection after deletion (see the
280 // early return in calculateTypingStyleAfterDelete).
281 if (m_upstreamStart.deprecatedNode() == m_downstreamEnd.deprecatedNode() && m_upstreamStart.deprecatedNode()->isTextNode())
284 // Figure out the typing style in effect before the delete is done.
285 m_typingStyle = EditingStyle::create(m_selectionToDelete.start());
286 m_typingStyle->removeStyleAddedByNode(enclosingAnchorElement(m_selectionToDelete.start()));
288 // If we're deleting into a Mail blockquote, save the style at end() instead of start()
289 // We'll use this later in computeTypingStyleAfterDelete if we end up outside of a Mail blockquote
290 if (enclosingNodeOfType(m_selectionToDelete.start(), isMailBlockquote))
291 m_deleteIntoBlockquoteStyle = EditingStyle::create(m_selectionToDelete.end());
293 m_deleteIntoBlockquoteStyle = 0;
296 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
298 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
299 bool upstreamStartIsBR = m_upstreamStart.deprecatedNode()->hasTagName(brTag);
300 bool downstreamStartIsBR = m_downstreamStart.deprecatedNode()->hasTagName(brTag);
301 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.deprecatedNode() == m_upstreamEnd.deprecatedNode();
302 if (isBROnLineByItself) {
303 removeNode(m_downstreamStart.deprecatedNode());
307 // Not a special-case delete per se, but we can detect that the merging of content between blocks
308 // should not be done.
309 if (upstreamStartIsBR && downstreamStartIsBR) {
310 m_startsAtEmptyLine = true;
311 m_endingPosition = m_downstreamEnd;
317 static void updatePositionForNodeRemoval(Node* node, Position& position)
319 if (position.isNull())
321 switch (position.anchorType()) {
322 case Position::PositionIsBeforeChildren:
323 if (position.containerNode() == node)
324 position = positionInParentBeforeNode(node);
326 case Position::PositionIsAfterChildren:
327 if (position.containerNode() == node)
328 position = positionInParentAfterNode(node);
330 case Position::PositionIsOffsetInAnchor:
331 if (position.containerNode() == node->parentNode() && static_cast<unsigned>(position.offsetInContainerNode()) > node->nodeIndex())
332 position.moveToOffset(position.offsetInContainerNode() - 1);
333 else if (node->contains(position.containerNode()))
334 position = positionInParentBeforeNode(node);
336 case Position::PositionIsAfterAnchor:
337 if (node->contains(position.anchorNode()))
338 position = positionInParentAfterNode(node);
340 case Position::PositionIsBeforeAnchor:
341 if (node->contains(position.anchorNode()))
342 position = positionInParentBeforeNode(node);
347 static Position firstEditablePositionInNode(Node* node)
351 while (next && !next->rendererIsEditable())
352 next = next->traverseNextNode(node);
353 return next ? firstPositionInOrBeforeNode(next) : Position();
356 void DeleteSelectionCommand::removeNode(PassRefPtr<Node> node)
361 if (m_startRoot != m_endRoot && !(node->isDescendantOf(m_startRoot.get()) && node->isDescendantOf(m_endRoot.get()))) {
362 // If a node is not in both the start and end editable roots, remove it only if its inside an editable region.
363 if (!node->parentNode()->rendererIsEditable()) {
364 // Don't remove non-editable atomic nodes.
365 if (!node->firstChild())
367 // Search this non-editable region for editable regions to empty.
368 RefPtr<Node> child = node->firstChild();
370 RefPtr<Node> nextChild = child->nextSibling();
371 removeNode(child.get());
372 // Bail if nextChild is no longer node's child.
373 if (nextChild && nextChild->parentNode() != node)
378 // Don't remove editable regions that are inside non-editable ones, just clear them.
383 if (isTableStructureNode(node.get()) || node == node->rootEditableElement()) {
384 // Do not remove an element of table structure; remove its contents.
385 // Likewise for the root editable element.
386 Node* child = node->firstChild();
388 Node* remove = child;
389 child = child->nextSibling();
393 // Make sure empty cell has some height, if a placeholder can be inserted.
395 RenderObject *r = node->renderer();
396 if (r && r->isTableCell() && toRenderTableCell(r)->contentHeight() <= 0) {
397 Position firstEditablePosition = firstEditablePositionInNode(node.get());
398 if (firstEditablePosition.isNotNull())
399 insertBlockPlaceholder(firstEditablePosition);
404 if (node == m_startBlock && !isEndOfBlock(VisiblePosition(firstPositionInNode(m_startBlock.get())).previous()))
405 m_needPlaceholder = true;
406 else if (node == m_endBlock && !isStartOfBlock(VisiblePosition(lastPositionInNode(m_startBlock.get())).next()))
407 m_needPlaceholder = true;
409 // FIXME: Update the endpoints of the range being deleted.
410 updatePositionForNodeRemoval(node.get(), m_endingPosition);
411 updatePositionForNodeRemoval(node.get(), m_leadingWhitespace);
412 updatePositionForNodeRemoval(node.get(), m_trailingWhitespace);
414 CompositeEditCommand::removeNode(node);
417 static void updatePositionForTextRemoval(Node* node, int offset, int count, Position& position)
419 if (position.anchorType() != Position::PositionIsOffsetInAnchor || position.containerNode() != node)
422 if (position.offsetInContainerNode() > offset + count)
423 position.moveToOffset(position.offsetInContainerNode() - count);
424 else if (position.offsetInContainerNode() > offset)
425 position.moveToOffset(offset);
428 void DeleteSelectionCommand::deleteTextFromNode(PassRefPtr<Text> node, unsigned offset, unsigned count)
430 // FIXME: Update the endpoints of the range being deleted.
431 updatePositionForTextRemoval(node.get(), offset, count, m_endingPosition);
432 updatePositionForTextRemoval(node.get(), offset, count, m_leadingWhitespace);
433 updatePositionForTextRemoval(node.get(), offset, count, m_trailingWhitespace);
434 updatePositionForTextRemoval(node.get(), offset, count, m_downstreamEnd);
436 CompositeEditCommand::deleteTextFromNode(node, offset, count);
439 void DeleteSelectionCommand::handleGeneralDelete()
441 int startOffset = m_upstreamStart.deprecatedEditingOffset();
442 Node* startNode = m_upstreamStart.deprecatedNode();
444 // Never remove the start block unless it's a table, in which case we won't merge content in.
445 if (startNode == m_startBlock && startOffset == 0 && canHaveChildrenForEditing(startNode) && !startNode->hasTagName(tableTag)) {
447 startNode = startNode->traverseNextNode();
450 if (startOffset >= caretMaxOffset(startNode) && startNode->isTextNode()) {
451 Text *text = static_cast<Text *>(startNode);
452 if (text->length() > (unsigned)caretMaxOffset(startNode))
453 deleteTextFromNode(text, caretMaxOffset(startNode), text->length() - caretMaxOffset(startNode));
456 if (startOffset >= lastOffsetForEditing(startNode)) {
457 startNode = startNode->traverseNextSibling();
461 // Done adjusting the start. See if we're all done.
465 if (startNode == m_downstreamEnd.deprecatedNode()) {
466 if (m_downstreamEnd.deprecatedEditingOffset() - startOffset > 0) {
467 if (startNode->isTextNode()) {
468 // in a text node that needs to be trimmed
469 Text* text = static_cast<Text*>(startNode);
470 deleteTextFromNode(text, startOffset, m_downstreamEnd.deprecatedEditingOffset() - startOffset);
472 removeChildrenInRange(startNode, startOffset, m_downstreamEnd.deprecatedEditingOffset());
473 m_endingPosition = m_upstreamStart;
477 // The selection to delete is all in one node.
478 if (!startNode->renderer() || (!startOffset && m_downstreamEnd.atLastEditingPositionForNode()))
479 removeNode(startNode);
482 bool startNodeWasDescendantOfEndNode = m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode());
483 // The selection to delete spans more than one node.
484 RefPtr<Node> node(startNode);
486 if (startOffset > 0) {
487 if (startNode->isTextNode()) {
488 // in a text node that needs to be trimmed
489 Text *text = static_cast<Text *>(node.get());
490 deleteTextFromNode(text, startOffset, text->length() - startOffset);
491 node = node->traverseNextNode();
493 node = startNode->childNode(startOffset);
495 } else if (startNode == m_upstreamEnd.deprecatedNode() && startNode->isTextNode()) {
496 Text* text = static_cast<Text*>(m_upstreamEnd.deprecatedNode());
497 deleteTextFromNode(text, 0, m_upstreamEnd.deprecatedEditingOffset());
500 // handle deleting all nodes that are completely selected
501 while (node && node != m_downstreamEnd.deprecatedNode()) {
502 if (comparePositions(firstPositionInOrBeforeNode(node.get()), m_downstreamEnd) >= 0) {
503 // traverseNextSibling just blew past the end position, so stop deleting
505 } else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
506 RefPtr<Node> nextNode = node->traverseNextSibling();
507 // if we just removed a node from the end container, update end position so the
508 // check above will work
509 updatePositionForNodeRemoval(node.get(), m_downstreamEnd);
510 removeNode(node.get());
511 node = nextNode.get();
513 Node* n = node->lastDescendant();
514 if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(n)) {
515 removeNode(node.get());
518 node = node->traverseNextNode();
522 if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.anchorNode()->inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
523 if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.deprecatedNode())) {
524 // The node itself is fully selected, not just its contents. Delete it.
525 removeNode(m_downstreamEnd.deprecatedNode());
527 if (m_downstreamEnd.deprecatedNode()->isTextNode()) {
528 // in a text node that needs to be trimmed
529 Text* text = static_cast<Text*>(m_downstreamEnd.deprecatedNode());
530 if (m_downstreamEnd.deprecatedEditingOffset() > 0) {
531 deleteTextFromNode(text, 0, m_downstreamEnd.deprecatedEditingOffset());
533 // Remove children of m_downstreamEnd.deprecatedNode() that come after m_upstreamStart.
534 // Don't try to remove children if m_upstreamStart was inside m_downstreamEnd.deprecatedNode()
535 // and m_upstreamStart has been removed from the document, because then we don't
536 // know how many children to remove.
537 // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
538 // always know which children to remove.
539 } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.anchorNode()->inDocument())) {
541 if (m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode())) {
542 Node* n = m_upstreamStart.deprecatedNode();
543 while (n && n->parentNode() != m_downstreamEnd.deprecatedNode())
546 offset = n->nodeIndex() + 1;
548 removeChildrenInRange(m_downstreamEnd.deprecatedNode(), offset, m_downstreamEnd.deprecatedEditingOffset());
549 m_downstreamEnd = createLegacyEditingPosition(m_downstreamEnd.deprecatedNode(), offset);
556 void DeleteSelectionCommand::fixupWhitespace()
559 // FIXME: isRenderedCharacter should be removed, and we should use VisiblePosition::characterAfter and VisiblePosition::characterBefore
560 if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharacter() && m_leadingWhitespace.deprecatedNode()->isTextNode()) {
561 Text* textNode = static_cast<Text*>(m_leadingWhitespace.deprecatedNode());
562 ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
563 replaceTextInNodePreservingMarkers(textNode, m_leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
565 if (m_trailingWhitespace.isNotNull() && !m_trailingWhitespace.isRenderedCharacter() && m_trailingWhitespace.deprecatedNode()->isTextNode()) {
566 Text* textNode = static_cast<Text*>(m_trailingWhitespace.deprecatedNode());
567 ASSERT(!textNode->renderer() ||textNode->renderer()->style()->collapseWhiteSpace());
568 replaceTextInNodePreservingMarkers(textNode, m_trailingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
572 // If a selection starts in one block and ends in another, we have to merge to bring content before the
573 // start together with content after the end.
574 void DeleteSelectionCommand::mergeParagraphs()
576 if (!m_mergeBlocksAfterDelete) {
577 if (m_pruneStartBlockIfNecessary) {
578 // We aren't going to merge into the start block, so remove it if it's empty.
580 // Removing the start block during a deletion is usually an indication that we need
581 // a placeholder, but not in this case.
582 m_needPlaceholder = false;
587 // It shouldn't have been asked to both try and merge content into the start block and prune it.
588 ASSERT(!m_pruneStartBlockIfNecessary);
590 // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
591 if (!m_downstreamEnd.anchorNode()->inDocument() || !m_upstreamStart.anchorNode()->inDocument())
594 // FIXME: The deletion algorithm shouldn't let this happen.
595 if (comparePositions(m_upstreamStart, m_downstreamEnd) > 0)
598 // There's nothing to merge.
599 if (m_upstreamStart == m_downstreamEnd)
602 VisiblePosition startOfParagraphToMove(m_downstreamEnd);
603 VisiblePosition mergeDestination(m_upstreamStart);
605 // m_downstreamEnd's block has been emptied out by deletion. There is no content inside of it to
606 // move, so just remove it.
607 Element* endBlock = static_cast<Element*>(enclosingBlock(m_downstreamEnd.deprecatedNode()));
608 if (!endBlock || !endBlock->contains(startOfParagraphToMove.deepEquivalent().deprecatedNode()) || !startOfParagraphToMove.deepEquivalent().deprecatedNode()) {
609 removeNode(enclosingBlock(m_downstreamEnd.deprecatedNode()));
613 // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
614 if (!mergeDestination.deepEquivalent().deprecatedNode() || !mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) || m_startsAtEmptyLine) {
615 insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
616 mergeDestination = VisiblePosition(m_upstreamStart);
619 if (mergeDestination == startOfParagraphToMove)
622 VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove);
624 if (mergeDestination == endOfParagraphToMove)
627 // The rule for merging into an empty block is: only do so if its farther to the right.
628 // FIXME: Consider RTL.
629 if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfParagraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds().x()) {
630 if (mergeDestination.deepEquivalent().downstream().deprecatedNode()->hasTagName(brTag)) {
631 removeNodeAndPruneAncestors(mergeDestination.deepEquivalent().downstream().deprecatedNode());
632 m_endingPosition = startOfParagraphToMove.deepEquivalent();
637 // Block images, tables and horizontal rules cannot be made inline with content at mergeDestination. If there is
638 // any (!isStartOfParagraph(mergeDestination)), don't merge, just move the caret to just before the selection we deleted.
639 // See https://bugs.webkit.org/show_bug.cgi?id=25439
640 if (isRenderedAsNonInlineTableImageOrHR(startOfParagraphToMove.deepEquivalent().deprecatedNode()) && !isStartOfParagraph(mergeDestination)) {
641 m_endingPosition = m_upstreamStart;
645 RefPtr<Range> range = Range::create(document(), startOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent(), endOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent());
646 RefPtr<Range> rangeToBeReplaced = Range::create(document(), mergeDestination.deepEquivalent().parentAnchoredEquivalent(), mergeDestination.deepEquivalent().parentAnchoredEquivalent());
647 if (!document()->frame()->editor()->client()->shouldMoveRangeAfterDelete(range.get(), rangeToBeReplaced.get()))
650 // moveParagraphs will insert placeholders if it removes blocks that would require their use, don't let block
651 // removals that it does cause the insertion of *another* placeholder.
652 bool needPlaceholder = m_needPlaceholder;
653 bool paragraphToMergeIsEmpty = (startOfParagraphToMove == endOfParagraphToMove);
654 moveParagraph(startOfParagraphToMove, endOfParagraphToMove, mergeDestination, false, !paragraphToMergeIsEmpty);
655 m_needPlaceholder = needPlaceholder;
656 // The endingPosition was likely clobbered by the move, so recompute it (moveParagraph selects the moved paragraph).
657 m_endingPosition = endingSelection().start();
660 void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows()
662 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
663 Node* row = m_endTableRow->previousSibling();
664 while (row && row != m_startTableRow) {
665 RefPtr<Node> previousRow = row->previousSibling();
666 if (isTableRowEmpty(row))
667 // Use a raw removeNode, instead of DeleteSelectionCommand's, because
668 // that won't remove rows, it only empties them in preparation for this function.
669 CompositeEditCommand::removeNode(row);
670 row = previousRow.get();
674 // Remove empty rows after the start row.
675 if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m_endTableRow) {
676 Node* row = m_startTableRow->nextSibling();
677 while (row && row != m_endTableRow) {
678 RefPtr<Node> nextRow = row->nextSibling();
679 if (isTableRowEmpty(row))
680 CompositeEditCommand::removeNode(row);
685 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow)
686 if (isTableRowEmpty(m_endTableRow.get())) {
687 // Don't remove m_endTableRow if it's where we're putting the ending selection.
688 if (!m_endingPosition.deprecatedNode()->isDescendantOf(m_endTableRow.get())) {
689 // FIXME: We probably shouldn't remove m_endTableRow unless it's fully selected, even if it is empty.
690 // We'll need to start adjusting the selection endpoints during deletion to know whether or not m_endTableRow
691 // was fully selected here.
692 CompositeEditCommand::removeNode(m_endTableRow.get());
697 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
702 // Compute the difference between the style before the delete and the style now
703 // after the delete has been done. Set this style on the frame, so other editing
704 // commands being composed with this one will work, and also cache it on the command,
705 // so the Frame::appliedEditing can set it after the whole composite command
708 // If we deleted into a blockquote, but are now no longer in a blockquote, use the alternate typing style
709 if (m_deleteIntoBlockquoteStyle && !enclosingNodeOfType(m_endingPosition, isMailBlockquote, CanCrossEditingBoundary))
710 m_typingStyle = m_deleteIntoBlockquoteStyle;
711 m_deleteIntoBlockquoteStyle = 0;
713 m_typingStyle->prepareToApplyAt(m_endingPosition);
714 if (m_typingStyle->isEmpty())
716 VisiblePosition visibleEnd(m_endingPosition);
718 isStartOfParagraph(visibleEnd) &&
719 isEndOfParagraph(visibleEnd) &&
720 lineBreakExistsAtVisiblePosition(visibleEnd)) {
721 // Apply style to the placeholder that is now holding open the empty paragraph.
722 // This makes sure that the paragraph has the right height, and that the paragraph
723 // takes on the right style and retains it even if you move the selection away and
724 // then move it back (which will clear typing style).
726 setEndingSelection(visibleEnd);
727 applyStyle(m_typingStyle.get(), EditActionUnspecified);
728 // applyStyle can destroy the placeholder that was at m_endingPosition if it needs to
729 // move it, but it will set an endingSelection() at [movedPlaceholder, 0] if it does so.
730 m_endingPosition = endingSelection().start();
733 // This is where we've deleted all traces of a style but not a whole paragraph (that's handled above).
734 // In this case if we start typing, the new characters should have the same style as the just deleted ones,
735 // but, if we change the selection, come back and start typing that style should be lost. Also see
736 // preserveTypingStyle() below.
737 document()->frame()->selection()->setTypingStyle(m_typingStyle);
740 void DeleteSelectionCommand::clearTransientState()
742 m_selectionToDelete = VisibleSelection();
743 m_upstreamStart.clear();
744 m_downstreamStart.clear();
745 m_upstreamEnd.clear();
746 m_downstreamEnd.clear();
747 m_endingPosition.clear();
748 m_leadingWhitespace.clear();
749 m_trailingWhitespace.clear();
752 String DeleteSelectionCommand::originalStringForAutocorrectionAtBeginningOfSelection()
754 if (!m_selectionToDelete.isRange())
757 VisiblePosition startOfSelection = m_selectionToDelete.start();
758 if (!isStartOfWord(startOfSelection))
761 VisiblePosition nextPosition = startOfSelection.next();
762 if (nextPosition.isNull())
765 RefPtr<Range> rangeOfFirstCharacter = Range::create(document(), startOfSelection.deepEquivalent(), nextPosition.deepEquivalent());
766 Vector<DocumentMarker*> markers = document()->markers()->markersInRange(rangeOfFirstCharacter.get(), DocumentMarker::Autocorrected);
767 for (size_t i = 0; i < markers.size(); ++i) {
768 const DocumentMarker* marker = markers[i];
769 int startOffset = marker->startOffset();
770 if (startOffset == startOfSelection.deepEquivalent().offsetInContainerNode())
771 return marker->description();
776 void DeleteSelectionCommand::doApply()
778 // If selection has not been set to a custom selection when the command was created,
779 // use the current ending selection.
780 if (!m_hasSelectionToDelete)
781 m_selectionToDelete = endingSelection();
783 if (!m_selectionToDelete.isNonOrphanedRange())
786 String originalString = originalStringForAutocorrectionAtBeginningOfSelection();
788 // 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.
790 Element* textControl = enclosingTextFormControl(m_selectionToDelete.start());
791 if (textControl && textControl->focused())
792 document()->frame()->editor()->textWillBeDeletedInTextField(textControl);
795 // save this to later make the selection with
796 EAffinity affinity = m_selectionToDelete.affinity();
798 Position downstreamEnd = m_selectionToDelete.end().downstream();
799 m_needPlaceholder = isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditingBoundary)
800 && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBoundary)
801 && !lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
802 if (m_needPlaceholder) {
803 // Don't need a placeholder when deleting a selection that starts just before a table
804 // and ends inside it (we do need placeholders to hold open empty cells, but that's
805 // handled elsewhere).
806 if (Node* table = isLastPositionBeforeTable(m_selectionToDelete.visibleStart()))
807 if (m_selectionToDelete.end().deprecatedNode()->isDescendantOf(table))
808 m_needPlaceholder = false;
813 initializePositionData();
815 // Delete any text that may hinder our ability to fixup whitespace after the delete
816 deleteInsignificantTextDownstream(m_trailingWhitespace);
818 saveTypingStyleState();
820 // deleting just a BR is handled specially, at least because we do not
821 // want to replace it with a placeholder BR!
822 if (handleSpecialCaseBRDelete()) {
823 calculateTypingStyleAfterDelete();
824 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
825 clearTransientState();
826 rebalanceWhitespace();
830 handleGeneralDelete();
836 removePreviouslySelectedEmptyTableRows();
838 RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
841 insertNodeAt(placeholder.get(), m_endingPosition);
843 rebalanceWhitespaceAt(m_endingPosition);
845 calculateTypingStyleAfterDelete();
847 if (!originalString.isEmpty()) {
848 if (Frame* frame = document()->frame())
849 frame->editor()->deletedAutocorrectionAtPosition(m_endingPosition, originalString);
852 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
853 clearTransientState();
856 EditAction DeleteSelectionCommand::editingAction() const
858 // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
859 // but in that case there's a TypingCommand that supplies the editingAction(), so
860 // the Undo menu correctly shows "Undo Typing"
861 return EditActionCut;
864 // Normally deletion doesn't preserve the typing style that was present before it. For example,
865 // type a character, Bold, then delete the character and start typing. The Bold typing style shouldn't
866 // stick around. Deletion should preserve a typing style that *it* sets, however.
867 bool DeleteSelectionCommand::preservesTypingStyle() const
869 return m_typingStyle;
872 } // namespace WebCore