DeleteSelectionCommand.cpp 39.4 KB
Newer Older
mjs's avatar
mjs committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright (C) 2005 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

mjs's avatar
mjs committed
26
#include "config.h"
darin's avatar
darin committed
27
#include "DeleteSelectionCommand.h"
mjs's avatar
mjs committed
28

darin's avatar
darin committed
29
#include "Document.h"
darin's avatar
darin committed
30
#include "DocumentFragment.h"
31
#include "EditingBoundary.h"
justing's avatar
justing committed
32
#include "Editor.h"
justing's avatar
justing committed
33
#include "EditorClient.h"
34
#include "Element.h"
mjs's avatar
mjs committed
35
#include "Frame.h"
darin's avatar
darin committed
36
#include "htmlediting.h"
adele's avatar
adele committed
37
#include "HTMLInputElement.h"
darin's avatar
darin committed
38
#include "HTMLNames.h"
hyatt@apple.com's avatar
hyatt@apple.com committed
39
#include "RenderTableCell.h"
darin's avatar
darin committed
40
#include "Text.h"
mjs's avatar
mjs committed
41
#include "visible_units.h"
darin's avatar
darin committed
42

darin's avatar
darin committed
43
namespace WebCore {
mjs's avatar
mjs committed
44

darin's avatar
darin committed
45
using namespace HTMLNames;
mjs's avatar
mjs committed
46

justing's avatar
justing committed
47
static bool isTableRow(const Node* node)
justing's avatar
justing committed
48 49 50 51
{
    return node && node->hasTagName(trTag);
}

52
static bool isTableCellEmpty(Node* cell)
justing's avatar
justing committed
53 54
{
    ASSERT(isTableCell(cell));
55
    return VisiblePosition(firstPositionInNode(cell)) == VisiblePosition(lastPositionInNode(cell));
justing's avatar
justing committed
56 57
}

58
static bool isTableRowEmpty(Node* row)
justing's avatar
justing committed
59 60 61 62 63 64 65 66 67 68 69
{
    if (!isTableRow(row))
        return false;
        
    for (Node* child = row->firstChild(); child; child = child->nextSibling())
        if (isTableCell(child) && !isTableCellEmpty(child))
            return false;
    
    return true;
}

justing's avatar
justing committed
70
DeleteSelectionCommand::DeleteSelectionCommand(Document *document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
mjs's avatar
mjs committed
71 72 73 74
    : CompositeEditCommand(document), 
      m_hasSelectionToDelete(false), 
      m_smartDelete(smartDelete), 
      m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
75
      m_needPlaceholder(false),
adele's avatar
adele committed
76
      m_replace(replace),
justing's avatar
justing committed
77
      m_expandForSpecialElements(expandForSpecialElements),
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
78
      m_pruneStartBlockIfNecessary(false),
mitz@apple.com's avatar
mitz@apple.com committed
79
      m_startsAtEmptyLine(false),
mjs's avatar
mjs committed
80 81
      m_startBlock(0),
      m_endBlock(0),
justing's avatar
justing committed
82 83
      m_typingStyle(0),
      m_deleteIntoBlockquoteStyle(0)
mjs's avatar
mjs committed
84 85 86
{
}

87
DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
88
    : CompositeEditCommand(selection.start().anchorNode()->document()), 
mjs's avatar
mjs committed
89 90 91
      m_hasSelectionToDelete(true), 
      m_smartDelete(smartDelete), 
      m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
92
      m_needPlaceholder(false),
adele's avatar
adele committed
93
      m_replace(replace),
justing's avatar
justing committed
94
      m_expandForSpecialElements(expandForSpecialElements),
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
95
      m_pruneStartBlockIfNecessary(false),
mitz@apple.com's avatar
mitz@apple.com committed
96
      m_startsAtEmptyLine(false),
mjs's avatar
mjs committed
97 98 99
      m_selectionToDelete(selection),
      m_startBlock(0),
      m_endBlock(0),
justing's avatar
justing committed
100 101
      m_typingStyle(0),
      m_deleteIntoBlockquoteStyle(0)
mjs's avatar
mjs committed
102 103 104
{
}

justing's avatar
justing committed
105
void DeleteSelectionCommand::initializeStartEnd(Position& start, Position& end)
darin's avatar
darin committed
106
{
darin's avatar
darin committed
107 108
    Node* startSpecialContainer = 0;
    Node* endSpecialContainer = 0;
harrison's avatar
harrison committed
109
 
justing's avatar
justing committed
110 111
    start = m_selectionToDelete.start();
    end = m_selectionToDelete.end();
justing's avatar
justing committed
112
 
justing's avatar
justing committed
113
    // 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,
lweintraub's avatar
lweintraub committed
114
    // but in these cases, we want to delete it, so manually expand the selection
115 116 117 118
    if (start.deprecatedNode()->hasTagName(hrTag))
        start = positionBeforeNode(start.deprecatedNode());
    else if (end.deprecatedNode()->hasTagName(hrTag))
        end = positionAfterNode(end.deprecatedNode());
lweintraub's avatar
lweintraub committed
119
    
120
    // FIXME: This is only used so that moveParagraphs can avoid the bugs in special element expansion.
justing's avatar
justing committed
121 122 123
    if (!m_expandForSpecialElements)
        return;
    
124
    while (1) {
justing's avatar
justing committed
125 126 127
        startSpecialContainer = 0;
        endSpecialContainer = 0;
    
justing's avatar
justing committed
128 129
        Position s = positionBeforeContainingSpecialElement(start, &startSpecialContainer);
        Position e = positionAfterContainingSpecialElement(end, &endSpecialContainer);
justing's avatar
justing committed
130
        
justing's avatar
justing committed
131
        if (!startSpecialContainer && !endSpecialContainer)
justing's avatar
justing committed
132
            break;
133 134 135
            
        if (VisiblePosition(start) != m_selectionToDelete.visibleStart() || VisiblePosition(end) != m_selectionToDelete.visibleEnd())
            break;
136

137 138
        // If we're going to expand to include the startSpecialContainer, it must be fully selected.
        if (startSpecialContainer && !endSpecialContainer && comparePositions(positionInParentAfterNode(startSpecialContainer), end) > -1)
justing's avatar
justing committed
139 140
            break;

141
        // If we're going to expand to include the endSpecialContainer, it must be fully selected.
142
        if (endSpecialContainer && !startSpecialContainer && comparePositions(start, positionInParentBeforeNode(endSpecialContainer)) > -1)
justing's avatar
justing committed
143
            break;
144

justing's avatar
justing committed
145
        if (startSpecialContainer && startSpecialContainer->isDescendantOf(endSpecialContainer))
justing's avatar
justing committed
146 147 148
            // Don't adjust the end yet, it is the end of a special element that contains the start
            // special element (which may or may not be fully selected).
            start = s;
justing's avatar
justing committed
149
        else if (endSpecialContainer && endSpecialContainer->isDescendantOf(startSpecialContainer))
justing's avatar
justing committed
150 151 152 153 154 155 156
            // Don't adjust the start yet, it is the start of a special element that contains the end
            // special element (which may or may not be fully selected).
            end = e;
        else {
            start = s;
            end = e;
        }
harrison's avatar
harrison committed
157 158 159
    }
}

160
void DeleteSelectionCommand::setStartingSelectionOnSmartDelete(const Position& start, const Position& end)
161 162 163 164 165 166 167 168 169 170 171 172 173
{
    VisiblePosition newBase;
    VisiblePosition newExtent;
    if (startingSelection().isBaseFirst()) {
        newBase = start;
        newExtent = end;
    } else {
        newBase = end;
        newExtent = start;        
    }
    setStartingSelection(VisibleSelection(newBase, newExtent));            
}
    
mjs's avatar
mjs committed
174 175
void DeleteSelectionCommand::initializePositionData()
{
justing's avatar
justing committed
176 177 178 179 180 181 182
    Position start, end;
    initializeStartEnd(start, end);
    
    m_upstreamStart = start.upstream();
    m_downstreamStart = start.downstream();
    m_upstreamEnd = end.upstream();
    m_downstreamEnd = end.downstream();
harrison's avatar
harrison committed
183
    
justing's avatar
justing committed
184 185 186
    m_startRoot = editableRootForPosition(start);
    m_endRoot = editableRootForPosition(end);
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
187 188
    m_startTableRow = enclosingNodeOfType(start, &isTableRow);
    m_endTableRow = enclosingNodeOfType(end, &isTableRow);
justing's avatar
justing committed
189
    
justing's avatar
justing committed
190
    // Don't move content out of a table cell.
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
191 192
    // If the cell is non-editable, enclosingNodeOfType won't return it by default, so
    // tell that function that we don't care if it returns non-editable nodes.
193 194
    Node* startCell = enclosingNodeOfType(m_upstreamStart, &isTableCell, CanCrossEditingBoundary);
    Node* endCell = enclosingNodeOfType(m_downstreamEnd, &isTableCell, CanCrossEditingBoundary);
justing's avatar
justing committed
195
    // FIXME: This isn't right.  A borderless table with two rows and a single column would appear as two paragraphs.
justing's avatar
justing committed
196
    if (endCell && endCell != startCell)
justing's avatar
justing committed
197 198
        m_mergeBlocksAfterDelete = false;
    
justing's avatar
justing committed
199
    // Usually the start and the end of the selection to delete are pulled together as a result of the deletion.
justing's avatar
justing committed
200 201
    // Sometimes they aren't (like when no merge is requested), so we must choose one position to hold the caret 
    // and receive the placeholder after deletion.
justing's avatar
justing committed
202 203 204 205 206
    VisiblePosition visibleEnd(m_downstreamEnd);
    if (m_mergeBlocksAfterDelete && !isEndOfParagraph(visibleEnd))
        m_endingPosition = m_downstreamEnd;
    else
        m_endingPosition = m_downstreamStart;
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
207 208 209 210 211
    
    // We don't want to merge into a block if it will mean changing the quote level of content after deleting 
    // selections that contain a whole number paragraphs plus a line break, since it is unclear to most users 
    // that such a selection actually ends at the start of the next paragraph. This matches TextEdit behavior 
    // for indented paragraphs.
adele@apple.com's avatar
adele@apple.com committed
212 213 214 215 216
    // Only apply this rule if the endingSelection is a range selection.  If it is a caret, then other operations have created
    // 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.
    if (numEnclosingMailBlockquotes(start) != numEnclosingMailBlockquotes(end) 
            && isStartOfParagraph(visibleEnd) && isStartOfParagraph(VisiblePosition(start)) 
            && endingSelection().isRange()) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
217 218 219
        m_mergeBlocksAfterDelete = false;
        m_pruneStartBlockIfNecessary = true;
    }
justing's avatar
justing committed
220

mjs's avatar
mjs committed
221
    // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
darin's avatar
darin committed
222
    m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity());
mjs's avatar
mjs committed
223 224 225 226 227
    m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);

    if (m_smartDelete) {
    
        // skip smart delete if the selection to delete already starts or ends with whitespace
darin's avatar
darin committed
228
        Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.affinity()).deepEquivalent();
mjs's avatar
mjs committed
229 230 231 232 233
        bool skipSmartDelete = pos.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
        if (!skipSmartDelete)
            skipSmartDelete = m_downstreamEnd.leadingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();

        // extend selection upstream if there is whitespace there
darin's avatar
darin committed
234
        bool hasLeadingWhitespaceBeforeAdjustment = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity(), true).isNotNull();
mjs's avatar
mjs committed
235
        if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
harrison's avatar
harrison committed
236
            VisiblePosition visiblePos = VisiblePosition(m_upstreamStart, VP_DEFAULT_AFFINITY).previous();
mjs's avatar
mjs committed
237 238 239 240 241 242
            pos = visiblePos.deepEquivalent();
            // Expand out one character upstream for smart delete and recalculate
            // positions based on this change.
            m_upstreamStart = pos.upstream();
            m_downstreamStart = pos.downstream();
            m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(visiblePos.affinity());
243 244

            setStartingSelectionOnSmartDelete(m_upstreamStart, m_upstreamEnd);
mjs's avatar
mjs committed
245 246 247 248 249 250 251
        }
        
        // trailing whitespace is only considered for smart delete if there is no leading
        // whitespace, as in the case where you double-click the first word of a paragraph.
        if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull()) {
            // Expand out one character downstream for smart delete and recalculate
            // positions based on this change.
harrison's avatar
harrison committed
252
            pos = VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY).next().deepEquivalent();
mjs's avatar
mjs committed
253 254 255
            m_upstreamEnd = pos.upstream();
            m_downstreamEnd = pos.downstream();
            m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
256 257

            setStartingSelectionOnSmartDelete(m_downstreamStart, m_downstreamEnd);
mjs's avatar
mjs committed
258 259 260
        }
    }
    
261
    // We must pass call parentAnchoredEquivalent on the positions since some editing positions
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
262
    // that appear inside their nodes aren't really inside them.  [hr, 0] is one example.
263
    // FIXME: parentAnchoredEquivalent should eventually be moved into enclosing element getters
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
264 265 266
    // like the one below, since editing functions should obviously accept editing positions.
    // FIXME: Passing false to enclosingNodeOfType tells it that it's OK to return a non-editable
    // node.  This was done to match existing behavior, but it seems wrong.
267 268
    m_startBlock = enclosingNodeOfType(m_downstreamStart.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
    m_endBlock = enclosingNodeOfType(m_upstreamEnd.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
mjs's avatar
mjs committed
269 270 271 272
}

void DeleteSelectionCommand::saveTypingStyleState()
{
273 274 275 276 277 278 279
    // A common case is deleting characters that are all from the same text node. In 
    // that case, the style at the start of the selection before deletion will be the 
    // same as the style at the start of the selection after deletion (since those
    // two positions will be identical). Therefore there is no need to save the
    // typing style at the start of the selection, nor is there a reason to 
    // compute the style at the start of the selection after deletion (see the 
    // early return in calculateTypingStyleAfterDelete).
280
    if (m_upstreamStart.deprecatedNode() == m_downstreamEnd.deprecatedNode() && m_upstreamStart.deprecatedNode()->isTextNode())
281
        return;
282

mjs's avatar
mjs committed
283
    // Figure out the typing style in effect before the delete is done.
284
    m_typingStyle = EditingStyle::create(m_selectionToDelete.start());
285
    m_typingStyle->removeStyleAddedByNode(enclosingAnchorElement(m_selectionToDelete.start()));
286

justing's avatar
justing committed
287 288
    // If we're deleting into a Mail blockquote, save the style at end() instead of start()
    // We'll use this later in computeTypingStyleAfterDelete if we end up outside of a Mail blockquote
289
    if (enclosingNodeOfType(m_selectionToDelete.start(), isMailBlockquote))
290
        m_deleteIntoBlockquoteStyle = EditingStyle::create(m_selectionToDelete.end());
291
    else
justing's avatar
justing committed
292
        m_deleteIntoBlockquoteStyle = 0;
mjs's avatar
mjs committed
293 294 295 296 297
}

bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
{
    // Check for special-case where the selection contains only a BR on a line by itself after another BR.
298 299 300
    bool upstreamStartIsBR = m_upstreamStart.deprecatedNode()->hasTagName(brTag);
    bool downstreamStartIsBR = m_downstreamStart.deprecatedNode()->hasTagName(brTag);
    bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.deprecatedNode() == m_upstreamEnd.deprecatedNode();
mjs's avatar
mjs committed
301
    if (isBROnLineByItself) {
302
        removeNode(m_downstreamStart.deprecatedNode());
mjs's avatar
mjs committed
303 304 305 306 307
        return true;
    }

    // Not a special-case delete per se, but we can detect that the merging of content between blocks
    // should not be done.
harrison's avatar
harrison committed
308
    if (upstreamStartIsBR && downstreamStartIsBR) {
mitz@apple.com's avatar
mitz@apple.com committed
309
        m_startsAtEmptyLine = true;
harrison's avatar
harrison committed
310 311 312
        m_endingPosition = m_downstreamEnd;
    }
    
mjs's avatar
mjs committed
313 314 315
    return false;
}

justing's avatar
justing committed
316 317 318 319
static void updatePositionForNodeRemoval(Node* node, Position& position)
{
    if (position.isNull())
        return;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    switch (position.anchorType()) {
    case Position::PositionIsOffsetInAnchor:
        if (position.containerNode() == node->parentNode() && static_cast<unsigned>(position.offsetInContainerNode()) > node->nodeIndex())
            position.moveToOffset(position.offsetInContainerNode() - 1);
        else if (node->contains(position.containerNode()))
            position = positionInParentBeforeNode(node);
        break;
    case Position::PositionIsAfterAnchor:
        if (node->contains(position.anchorNode()))
            position = positionInParentAfterNode(node);
        break;
    case Position::PositionIsBeforeAnchor:
        if (node->contains(position.anchorNode()))
            position = positionInParentBeforeNode(node);
        break;
    }
justing's avatar
justing committed
336 337
}

338 339 340 341 342 343 344 345 346
static Position firstEditablePositionInNode(Node* node)
{
    ASSERT(node);
    Node* next = node;
    while (next && !next->rendererIsEditable())
        next = next->traverseNextNode(node);
    return next ? firstPositionInOrBeforeNode(next) : Position();
}

347
void DeleteSelectionCommand::removeNode(PassRefPtr<Node> node)
justing's avatar
justing committed
348
{
justing's avatar
justing committed
349 350 351 352 353
    if (!node)
        return;
        
    if (m_startRoot != m_endRoot && !(node->isDescendantOf(m_startRoot.get()) && node->isDescendantOf(m_endRoot.get()))) {
        // If a node is not in both the start and end editable roots, remove it only if its inside an editable region.
354
        if (!node->parentNode()->rendererIsEditable()) {
justing's avatar
justing committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
            // Don't remove non-editable atomic nodes.
            if (!node->firstChild())
                return;
            // Search this non-editable region for editable regions to empty.
            RefPtr<Node> child = node->firstChild();
            while (child) {
                RefPtr<Node> nextChild = child->nextSibling();
                removeNode(child.get());
                // Bail if nextChild is no longer node's child.
                if (nextChild && nextChild->parentNode() != node)
                    return;
                child = nextChild;
            }
            
            // Don't remove editable regions that are inside non-editable ones, just clear them.
            return;
        }
    }
    
374
    if (isTableStructureNode(node.get()) || node == node->rootEditableElement()) {
justing's avatar
justing committed
375 376
        // Do not remove an element of table structure; remove its contents.
        // Likewise for the root editable element.
377
        Node* child = node->firstChild();
justing's avatar
justing committed
378
        while (child) {
379
            Node* remove = child;
justing's avatar
justing committed
380
            child = child->nextSibling();
justing's avatar
justing committed
381
            removeNode(remove);
justing's avatar
justing committed
382 383
        }
        
384
        // Make sure empty cell has some height, if a placeholder can be inserted.
justing's avatar
justing committed
385 386
        updateLayout();
        RenderObject *r = node->renderer();
387 388 389 390 391
        if (r && r->isTableCell() && toRenderTableCell(r)->contentHeight() <= 0) {
            Position firstEditablePosition = firstEditablePositionInNode(node.get());
            if (firstEditablePosition.isNotNull())
                insertBlockPlaceholder(firstEditablePosition);
        }
justing's avatar
justing committed
392 393 394
        return;
    }
    
395
    if (node == m_startBlock && !isEndOfBlock(VisiblePosition(firstPositionInNode(m_startBlock.get())).previous()))
lweintraub's avatar
lweintraub committed
396
        m_needPlaceholder = true;
397
    else if (node == m_endBlock && !isStartOfBlock(VisiblePosition(lastPositionInNode(m_startBlock.get())).next()))
lweintraub's avatar
lweintraub committed
398 399
        m_needPlaceholder = true;
    
justing's avatar
justing committed
400
    // FIXME: Update the endpoints of the range being deleted.
401 402 403
    updatePositionForNodeRemoval(node.get(), m_endingPosition);
    updatePositionForNodeRemoval(node.get(), m_leadingWhitespace);
    updatePositionForNodeRemoval(node.get(), m_trailingWhitespace);
justing's avatar
justing committed
404
    
justing's avatar
justing committed
405
    CompositeEditCommand::removeNode(node);
justing's avatar
justing committed
406 407
}

408
static void updatePositionForTextRemoval(Node* node, int offset, int count, Position& position)
justing's avatar
justing committed
409
{
410 411 412 413 414 415 416
    if (position.anchorType() != Position::PositionIsOffsetInAnchor || position.containerNode() != node)
        return;

    if (position.offsetInContainerNode() > offset + count)
        position.moveToOffset(position.offsetInContainerNode() - count);
    else if (position.offsetInContainerNode() > offset)
        position.moveToOffset(offset);
justing's avatar
justing committed
417 418
}

419
void DeleteSelectionCommand::deleteTextFromNode(PassRefPtr<Text> node, unsigned offset, unsigned count)
justing's avatar
justing committed
420 421
{
    // FIXME: Update the endpoints of the range being deleted.
422 423 424
    updatePositionForTextRemoval(node.get(), offset, count, m_endingPosition);
    updatePositionForTextRemoval(node.get(), offset, count, m_leadingWhitespace);
    updatePositionForTextRemoval(node.get(), offset, count, m_trailingWhitespace);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
425
    updatePositionForTextRemoval(node.get(), offset, count, m_downstreamEnd);
justing's avatar
justing committed
426 427 428 429
    
    CompositeEditCommand::deleteTextFromNode(node, offset, count);
}

mjs's avatar
mjs committed
430 431
void DeleteSelectionCommand::handleGeneralDelete()
{
eric@webkit.org's avatar
eric@webkit.org committed
432
    int startOffset = m_upstreamStart.deprecatedEditingOffset();
433
    Node* startNode = m_upstreamStart.deprecatedNode();
lweintraub's avatar
lweintraub committed
434 435 436
    
    // Never remove the start block unless it's a table, in which case we won't merge content in.
    if (startNode == m_startBlock && startOffset == 0 && canHaveChildrenForEditing(startNode) && !startNode->hasTagName(tableTag)) {
justing's avatar
justing committed
437
        startOffset = 0;
justing's avatar
justing committed
438
        startNode = startNode->traverseNextNode();
justing's avatar
justing committed
439
    }
mjs's avatar
mjs committed
440

ap@webkit.org's avatar
ap@webkit.org committed
441
    if (startOffset >= caretMaxOffset(startNode) && startNode->isTextNode()) {
justing's avatar
justing committed
442
        Text *text = static_cast<Text *>(startNode);
ap@webkit.org's avatar
ap@webkit.org committed
443 444
        if (text->length() > (unsigned)caretMaxOffset(startNode))
            deleteTextFromNode(text, caretMaxOffset(startNode), text->length() - caretMaxOffset(startNode));
mjs's avatar
mjs committed
445 446
    }

eric@webkit.org's avatar
eric@webkit.org committed
447
    if (startOffset >= lastOffsetForEditing(startNode)) {
justing's avatar
justing committed
448
        startNode = startNode->traverseNextSibling();
mjs's avatar
mjs committed
449 450 451 452
        startOffset = 0;
    }

    // Done adjusting the start.  See if we're all done.
justing's avatar
justing committed
453
    if (!startNode)
mjs's avatar
mjs committed
454 455
        return;

456
    if (startNode == m_downstreamEnd.deprecatedNode()) {
457
        if (m_downstreamEnd.deprecatedEditingOffset() - startOffset > 0) {
justing's avatar
justing committed
458
            if (startNode->isTextNode()) {
mjs's avatar
mjs committed
459
                // in a text node that needs to be trimmed
eric@webkit.org's avatar
eric@webkit.org committed
460
                Text* text = static_cast<Text*>(startNode);
eric@webkit.org's avatar
eric@webkit.org committed
461
                deleteTextFromNode(text, startOffset, m_downstreamEnd.deprecatedEditingOffset() - startOffset);
mjs's avatar
mjs committed
462
            } else {
eric@webkit.org's avatar
eric@webkit.org committed
463
                removeChildrenInRange(startNode, startOffset, m_downstreamEnd.deprecatedEditingOffset());
mjs's avatar
mjs committed
464 465 466
                m_endingPosition = m_upstreamStart;
            }
        }
467 468 469 470

        // The selection to delete is all in one node.
        if (!startNode->renderer() || (!startOffset && m_downstreamEnd.atLastEditingPositionForNode()))
            removeNode(startNode);
mjs's avatar
mjs committed
471 472
    }
    else {
473
        bool startNodeWasDescendantOfEndNode = m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode());
mjs's avatar
mjs committed
474
        // The selection to delete spans more than one node.
justing's avatar
justing committed
475
        RefPtr<Node> node(startNode);
mjs's avatar
mjs committed
476 477
        
        if (startOffset > 0) {
justing's avatar
justing committed
478
            if (startNode->isTextNode()) {
mjs's avatar
mjs committed
479
                // in a text node that needs to be trimmed
justing's avatar
justing committed
480
                Text *text = static_cast<Text *>(node.get());
mjs's avatar
mjs committed
481 482 483
                deleteTextFromNode(text, startOffset, text->length() - startOffset);
                node = node->traverseNextNode();
            } else {
justing's avatar
justing committed
484
                node = startNode->childNode(startOffset);
mjs's avatar
mjs committed
485
            }
486 487
        } else if (startNode == m_upstreamEnd.deprecatedNode() && startNode->isTextNode()) {
            Text* text = static_cast<Text*>(m_upstreamEnd.deprecatedNode());
488
            deleteTextFromNode(text, 0, m_upstreamEnd.deprecatedEditingOffset());
mjs's avatar
mjs committed
489 490 491
        }
        
        // handle deleting all nodes that are completely selected
492
        while (node && node != m_downstreamEnd.deprecatedNode()) {
493
            if (comparePositions(firstPositionInOrBeforeNode(node.get()), m_downstreamEnd) >= 0) {
mjs's avatar
mjs committed
494 495
                // traverseNextSibling just blew past the end position, so stop deleting
                node = 0;
496
            } else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
justing's avatar
justing committed
497
                RefPtr<Node> nextNode = node->traverseNextSibling();
mjs's avatar
mjs committed
498 499
                // if we just removed a node from the end container, update end position so the
                // check above will work
500
                if (node->parentNode() == m_downstreamEnd.deprecatedNode()) {
501
                    ASSERT(m_downstreamEnd.deprecatedEditingOffset());
eric@webkit.org's avatar
eric@webkit.org committed
502
                    ASSERT(node->nodeIndex() < (unsigned)m_downstreamEnd.deprecatedEditingOffset());
503
                    m_downstreamEnd.moveToOffset(m_downstreamEnd.deprecatedEditingOffset() - 1);
mjs's avatar
mjs committed
504
                }
justing's avatar
justing committed
505
                removeNode(node.get());
justing's avatar
justing committed
506
                node = nextNode.get();
mjs's avatar
mjs committed
507
            } else {
justing's avatar
justing committed
508
                Node* n = node->lastDescendant();
509
                if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(n)) {
justing's avatar
justing committed
510
                    removeNode(node.get());
mjs's avatar
mjs committed
511
                    node = 0;
justing's avatar
justing committed
512
                } else
mjs's avatar
mjs committed
513 514 515 516
                    node = node->traverseNextNode();
            }
        }
        
517 518
        if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.anchorNode()->inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
            if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.deprecatedNode())) {
justing's avatar
justing committed
519
                // The node itself is fully selected, not just its contents.  Delete it.
520
                removeNode(m_downstreamEnd.deprecatedNode());
mjs's avatar
mjs committed
521
            } else {
522
                if (m_downstreamEnd.deprecatedNode()->isTextNode()) {
mjs's avatar
mjs committed
523
                    // in a text node that needs to be trimmed
524
                    Text* text = static_cast<Text*>(m_downstreamEnd.deprecatedNode());
eric@webkit.org's avatar
eric@webkit.org committed
525 526
                    if (m_downstreamEnd.deprecatedEditingOffset() > 0) {
                        deleteTextFromNode(text, 0, m_downstreamEnd.deprecatedEditingOffset());
mjs's avatar
mjs committed
527
                    }
528 529
                // Remove children of m_downstreamEnd.deprecatedNode() that come after m_upstreamStart.
                // Don't try to remove children if m_upstreamStart was inside m_downstreamEnd.deprecatedNode()
justing's avatar
justing committed
530 531 532 533
                // and m_upstreamStart has been removed from the document, because then we don't 
                // know how many children to remove.
                // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
                // always know which children to remove.
534
                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.anchorNode()->inDocument())) {
mjs's avatar
mjs committed
535
                    int offset = 0;
536 537 538
                    if (m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode())) {
                        Node* n = m_upstreamStart.deprecatedNode();
                        while (n && n->parentNode() != m_downstreamEnd.deprecatedNode())
mjs's avatar
mjs committed
539 540 541 542
                            n = n->parentNode();
                        if (n)
                            offset = n->nodeIndex() + 1;
                    }
543
                    removeChildrenInRange(m_downstreamEnd.deprecatedNode(), offset, m_downstreamEnd.deprecatedEditingOffset());
544
                    m_downstreamEnd.moveToOffset(offset);
mjs's avatar
mjs committed
545 546 547 548 549 550 551 552
                }
            }
        }
    }
}

void DeleteSelectionCommand::fixupWhitespace()
{
darin's avatar
darin committed
553
    updateLayout();
justing's avatar
justing committed
554
    // FIXME: isRenderedCharacter should be removed, and we should use VisiblePosition::characterAfter and VisiblePosition::characterBefore
555 556
    if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharacter() && m_leadingWhitespace.deprecatedNode()->isTextNode()) {
        Text* textNode = static_cast<Text*>(m_leadingWhitespace.deprecatedNode());
darin's avatar
darin committed
557
        ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
eric@webkit.org's avatar
eric@webkit.org committed
558
        replaceTextInNode(textNode, m_leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
mjs's avatar
mjs committed
559
    }
560 561
    if (m_trailingWhitespace.isNotNull() && !m_trailingWhitespace.isRenderedCharacter() && m_trailingWhitespace.deprecatedNode()->isTextNode()) {
        Text* textNode = static_cast<Text*>(m_trailingWhitespace.deprecatedNode());
darin's avatar
darin committed
562
        ASSERT(!textNode->renderer() ||textNode->renderer()->style()->collapseWhiteSpace());
eric@webkit.org's avatar
eric@webkit.org committed
563
        replaceTextInNode(textNode, m_trailingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
mjs's avatar
mjs committed
564 565 566
    }
}

justing's avatar
justing committed
567 568
// If a selection starts in one block and ends in another, we have to merge to bring content before the
// start together with content after the end.
justing's avatar
justing committed
569
void DeleteSelectionCommand::mergeParagraphs()
mjs's avatar
mjs committed
570
{
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
571 572 573
    if (!m_mergeBlocksAfterDelete) {
        if (m_pruneStartBlockIfNecessary) {
            // We aren't going to merge into the start block, so remove it if it's empty.
mitz@apple.com's avatar
mitz@apple.com committed
574
            prune(m_startBlock);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
575 576 577 578
            // Removing the start block during a deletion is usually an indication that we need
            // a placeholder, but not in this case.
            m_needPlaceholder = false;
        }
mjs's avatar
mjs committed
579
        return;
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
580 581 582 583
    }
    
    // It shouldn't have been asked to both try and merge content into the start block and prune it.
    ASSERT(!m_pruneStartBlockIfNecessary);
mjs's avatar
mjs committed
584

justing's avatar
justing committed
585
    // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
586
    if (!m_downstreamEnd.anchorNode()->inDocument() || !m_upstreamStart.anchorNode()->inDocument())
justing's avatar
justing committed
587 588
         return;
         
justing's avatar
justing committed
589
    // FIXME: The deletion algorithm shouldn't let this happen.
590
    if (comparePositions(m_upstreamStart, m_downstreamEnd) > 0)
justing's avatar
justing committed
591 592
        return;
        
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
593 594
    // There's nothing to merge.
    if (m_upstreamStart == m_downstreamEnd)
justing's avatar
justing committed
595 596
        return;
        
justing's avatar
justing committed
597 598
    VisiblePosition startOfParagraphToMove(m_downstreamEnd);
    VisiblePosition mergeDestination(m_upstreamStart);
harrison's avatar
harrison committed
599
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
600 601
    // m_downstreamEnd's block has been emptied out by deletion.  There is no content inside of it to
    // move, so just remove it.
602 603 604
    Element* endBlock = static_cast<Element*>(enclosingBlock(m_downstreamEnd.deprecatedNode()));
    if (!startOfParagraphToMove.deepEquivalent().deprecatedNode() || !endBlock->contains(startOfParagraphToMove.deepEquivalent().deprecatedNode())) {
        removeNode(enclosingBlock(m_downstreamEnd.deprecatedNode()));
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
605 606 607
        return;
    }
    
justing's avatar
justing committed
608
    // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
609
    if (!mergeDestination.deepEquivalent().deprecatedNode() || !mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) || m_startsAtEmptyLine) {
justing's avatar
justing committed
610
        insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
justing's avatar
justing committed
611 612
        mergeDestination = VisiblePosition(m_upstreamStart);
    }
justing's avatar
justing committed
613
    
justing's avatar
justing committed
614
    if (mergeDestination == startOfParagraphToMove)
justing's avatar
justing committed
615 616 617 618
        return;
        
    VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove);
    
darin's avatar
darin committed
619 620
    if (mergeDestination == endOfParagraphToMove)
        return;
mjs's avatar
mjs committed
621
    
justing's avatar
justing committed
622 623
    // The rule for merging into an empty block is: only do so if its farther to the right.
    // FIXME: Consider RTL.
mitz@apple.com's avatar
mitz@apple.com committed
624
    if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfParagraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds().x()) {
625 626
        if (mergeDestination.deepEquivalent().downstream().deprecatedNode()->hasTagName(brTag)) {
            removeNodeAndPruneAncestors(mergeDestination.deepEquivalent().downstream().deprecatedNode());
627 628 629
            m_endingPosition = startOfParagraphToMove.deepEquivalent();
            return;
        }
justing's avatar
justing committed
630 631
    }
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
632 633 634
    // Block images, tables and horizontal rules cannot be made inline with content at mergeDestination.  If there is 
    // any (!isStartOfParagraph(mergeDestination)), don't merge, just move the caret to just before the selection we deleted.
    // See https://bugs.webkit.org/show_bug.cgi?id=25439
635
    if (isRenderedAsNonInlineTableImageOrHR(startOfParagraphToMove.deepEquivalent().deprecatedNode()) && !isStartOfParagraph(mergeDestination)) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
636 637 638 639
        m_endingPosition = m_upstreamStart;
        return;
    }
    
640 641
    RefPtr<Range> range = Range::create(document(), startOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent(), endOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent());
    RefPtr<Range> rangeToBeReplaced = Range::create(document(), mergeDestination.deepEquivalent().parentAnchoredEquivalent(), mergeDestination.deepEquivalent().parentAnchoredEquivalent());
justing's avatar
justing committed
642 643 644
    if (!document()->frame()->editor()->client()->shouldMoveRangeAfterDelete(range.get(), rangeToBeReplaced.get()))
        return;
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
645 646 647
    // moveParagraphs will insert placeholders if it removes blocks that would require their use, don't let block
    // removals that it does cause the insertion of *another* placeholder.
    bool needPlaceholder = m_needPlaceholder;
648 649
    bool paragraphToMergeIsEmpty = (startOfParagraphToMove == endOfParagraphToMove);
    moveParagraph(startOfParagraphToMove, endOfParagraphToMove, mergeDestination, false, !paragraphToMergeIsEmpty);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
650
    m_needPlaceholder = needPlaceholder;
justing's avatar
justing committed
651
    // The endingPosition was likely clobbered by the move, so recompute it (moveParagraph selects the moved paragraph).
justing's avatar
justing committed
652
    m_endingPosition = endingSelection().start();
mjs's avatar
mjs committed
653 654
}

justing's avatar
justing committed
655 656
void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows()
{
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
657 658 659
    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
        Node* row = m_endTableRow->previousSibling();
        while (row && row != m_startTableRow) {
justing's avatar
justing committed
660 661 662 663 664 665 666 667 668
            RefPtr<Node> previousRow = row->previousSibling();
            if (isTableRowEmpty(row))
                // Use a raw removeNode, instead of DeleteSelectionCommand's, because
                // that won't remove rows, it only empties them in preparation for this function.
                CompositeEditCommand::removeNode(row);
            row = previousRow.get();
        }
    }
    
justing's avatar
justing committed
669 670
    // Remove empty rows after the start row.
    if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m_endTableRow) {
justing's avatar
justing committed
671
        Node* row = m_startTableRow->nextSibling();
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
672
        while (row && row != m_endTableRow) {
justing's avatar
justing committed
673 674 675 676 677 678
            RefPtr<Node> nextRow = row->nextSibling();
            if (isTableRowEmpty(row))
                CompositeEditCommand::removeNode(row);
            row = nextRow.get();
        }
    }
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
679 680 681 682
    
    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow)
        if (isTableRowEmpty(m_endTableRow.get())) {
            // Don't remove m_endTableRow if it's where we're putting the ending selection.
683
            if (!m_endingPosition.deprecatedNode()->isDescendantOf(m_endTableRow.get())) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
684 685 686 687 688 689
                // FIXME: We probably shouldn't remove m_endTableRow unless it's fully selected, even if it is empty.
                // We'll need to start adjusting the selection endpoints during deletion to know whether or not m_endTableRow
                // was fully selected here.
                CompositeEditCommand::removeNode(m_endTableRow.get());
            }
        }
justing's avatar
justing committed
690 691
}

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
692
void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
mjs's avatar
mjs committed
693
{
694 695 696
    if (!m_typingStyle)
        return;
        
mjs's avatar
mjs committed
697
    // Compute the difference between the style before the delete and the style now
mjs's avatar
mjs committed
698
    // after the delete has been done. Set this style on the frame, so other editing
mjs's avatar
mjs committed
699
    // commands being composed with this one will work, and also cache it on the command,
mjs's avatar
mjs committed
700
    // so the Frame::appliedEditing can set it after the whole composite command 
mjs's avatar
mjs committed
701
    // has completed.
justing's avatar
justing committed
702
    
eseidel's avatar
eseidel committed
703
    // If we deleted into a blockquote, but are now no longer in a blockquote, use the alternate typing style
704
    if (m_deleteIntoBlockquoteStyle && !enclosingNodeOfType(m_endingPosition, isMailBlockquote, CanCrossEditingBoundary))
eseidel's avatar
eseidel committed
705 706
        m_typingStyle = m_deleteIntoBlockquoteStyle;
    m_deleteIntoBlockquoteStyle = 0;
707

708 709
    m_typingStyle->prepareToApplyAt(m_endingPosition);
    if (m_typingStyle->isEmpty())
mjs's avatar
mjs committed
710
        m_typingStyle = 0;
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
711 712 713 714
    VisiblePosition visibleEnd(m_endingPosition);
    if (m_typingStyle && 
        isStartOfParagraph(visibleEnd) &&
        isEndOfParagraph(visibleEnd) &&
715
        lineBreakExistsAtVisiblePosition(visibleEnd)) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
716 717 718 719 720 721
        // Apply style to the placeholder that is now holding open the empty paragraph. 
        // This makes sure that the paragraph has the right height, and that the paragraph 
        // takes on the right style and retains it even if you move the selection away and
        // then move it back (which will clear typing style).

        setEndingSelection(visibleEnd);
722
        applyStyle(m_typingStyle.get(), EditActionUnspecified);
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
723 724 725
        // applyStyle can destroy the placeholder that was at m_endingPosition if it needs to 
        // move it, but it will set an endingSelection() at [movedPlaceholder, 0] if it does so.
        m_endingPosition = endingSelection().start();
mjs's avatar
mjs committed
726 727
        m_typingStyle = 0;
    }
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
728 729 730 731
    // This is where we've deleted all traces of a style but not a whole paragraph (that's handled above).
    // In this case if we start typing, the new characters should have the same style as the just deleted ones,
    // but, if we change the selection, come back and start typing that style should be lost.  Also see 
    // preserveTypingStyle() below.
732
    document()->frame()->selection()->setTypingStyle(m_typingStyle);
mjs's avatar
mjs committed
733 734 735 736
}

void DeleteSelectionCommand::clearTransientState()
{
737
    m_selectionToDelete = VisibleSelection();
mjs's avatar
mjs committed
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    m_upstreamStart.clear();
    m_downstreamStart.clear();
    m_upstreamEnd.clear();
    m_downstreamEnd.clear();
    m_endingPosition.clear();
    m_leadingWhitespace.clear();
    m_trailingWhitespace.clear();
}

void DeleteSelectionCommand::doApply()
{
    // If selection has not been set to a custom selection when the command was created,
    // use the current ending selection.
    if (!m_hasSelectionToDelete)
        m_selectionToDelete = endingSelection();
753 754

    if (!m_selectionToDelete.isNonOrphanedRange())
mjs's avatar
mjs committed
755 756
        return;

adele's avatar
adele committed
757 758
    // 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. 
    if (!m_replace) {
759
        Node* startNode = m_selectionToDelete.start().deprecatedNode();
adele's avatar
adele committed
760
        Node* ancestorNode = startNode ? startNode->shadowAncestorNode() : 0;
darin's avatar
darin committed
761 762 763
        if (ancestorNode && ancestorNode->hasTagName(inputTag)
                && static_cast<HTMLInputElement*>(ancestorNode)->isTextField()
                && ancestorNode->focused())
764
            document()->frame()->editor()->textWillBeDeletedInTextField(static_cast<Element*>(ancestorNode));
adele's avatar
adele committed
765
    }
adele's avatar
adele committed
766

mjs's avatar
mjs committed
767
    // save this to later make the selection with
darin's avatar
darin committed
768
    EAffinity affinity = m_selectionToDelete.affinity();
mjs's avatar
mjs committed
769
    
justing's avatar
justing committed
770
    Position downstreamEnd = m_selectionToDelete.end().downstream();
771 772
    m_needPlaceholder = isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditingBoundary)
            && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBoundary)
773
            && !lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
justing's avatar
justing committed
774 775 776 777 778
    if (m_needPlaceholder) {
        // Don't need a placeholder when deleting a selection that starts just before a table
        // and ends inside it (we do need placeholders to hold open empty cells, but that's
        // handled elsewhere).
        if (Node* table = isLastPositionBeforeTable(m_selectionToDelete.visibleStart()))
779
            if (m_selectionToDelete.end().deprecatedNode()->isDescendantOf(table))
justing's avatar
justing committed
780 781 782
                m_needPlaceholder = false;
    }
        
justing's avatar
justing committed
783
    
mjs's avatar
mjs committed
784 785
    // set up our state
    initializePositionData();
harrison's avatar
harrison committed
786

787
    // Delete any text that may hinder our ability to fixup whitespace after the delete
harrison's avatar
harrison committed
788 789 790
    deleteInsignificantTextDownstream(m_trailingWhitespace);    

    saveTypingStyleState();
mjs's avatar
mjs committed
791
    
harrison's avatar
harrison committed
792 793 794
    // deleting just a BR is handled specially, at least because we do not
    // want to replace it with a placeholder BR!
    if (handleSpecialCaseBRDelete()) {
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
795
        calculateTypingStyleAfterDelete();
796
        setEndingSelection(VisibleSelection(m_endingPosition, affinity));
harrison's avatar
harrison committed
797 798 799 800
        clearTransientState();
        rebalanceWhitespace();
        return;
    }
mjs's avatar
mjs committed
801
    
harrison's avatar
harrison committed
802
    handleGeneralDelete();
mjs's avatar
mjs committed
803 804 805
    
    fixupWhitespace();
    
justing's avatar
justing committed
806 807
    mergeParagraphs();
    
justing's avatar
justing committed
808 809
    removePreviouslySelectedEmptyTableRows();
    
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
810 811
    RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
    
justing's avatar
justing committed
812
    if (placeholder)
justing's avatar
justing committed
813
        insertNodeAt(placeholder.get(), m_endingPosition);
harrison's avatar
harrison committed
814

justing's avatar
justing committed
815 816
    rebalanceWhitespaceAt(m_endingPosition);

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
817
    calculateTypingStyleAfterDelete();
justing's avatar
justing committed
818
    
819
    setEndingSelection(VisibleSelection(m_endingPosition, affinity));
mjs's avatar
mjs committed
820 821 822 823 824 825 826 827 828 829 830
    clearTransientState();
}

EditAction DeleteSelectionCommand::editingAction() const
{
    // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
    // but in that case there's a TypingCommand that supplies the editingAction(), so
    // the Undo menu correctly shows "Undo Typing"
    return EditActionCut;
}

justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
831 832 833
// Normally deletion doesn't preserve the typing style that was present before it.  For example,
// type a character, Bold, then delete the character and start typing.  The Bold typing style shouldn't
// stick around.  Deletion should preserve a typing style that *it* sets, however.
mjs's avatar
mjs committed
834 835
bool DeleteSelectionCommand::preservesTypingStyle() const
{
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
836
    return m_typingStyle;
mjs's avatar
mjs committed
837 838
}

darin's avatar
darin committed
839
} // namespace WebCore