2 * Copyright (C) 2004 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.
26 #include "htmlediting.h"
28 #include "css_computedstyle.h"
29 #include "css_value.h"
30 #include "css_valueimpl.h"
31 #include "cssproperties.h"
33 #include "dom_docimpl.h"
34 #include "dom_docimpl.h"
35 #include "dom_elementimpl.h"
36 #include "dom_nodeimpl.h"
37 #include "dom_position.h"
38 #include "dom_positioniterator.h"
39 #include "dom_stringimpl.h"
40 #include "dom_textimpl.h"
41 #include "dom2_rangeimpl.h"
42 #include "html_elementimpl.h"
43 #include "html_imageimpl.h"
44 #include "html_interchange.h"
45 #include "htmlattrs.h"
47 #include "khtml_part.h"
48 #include "khtml_part.h"
49 #include "khtmlview.h"
51 #include "render_object.h"
52 #include "render_style.h"
53 #include "render_text.h"
54 #include "visible_position.h"
55 #include "visible_units.h"
58 using DOM::CSSComputedStyleDeclarationImpl;
59 using DOM::CSSMutableStyleDeclarationImpl;
60 using DOM::CSSPrimitiveValue;
61 using DOM::CSSPrimitiveValueImpl;
62 using DOM::CSSProperty;
63 using DOM::CSSStyleDeclarationImpl;
64 using DOM::CSSValueImpl;
65 using DOM::DocumentFragmentImpl;
66 using DOM::DocumentImpl;
68 using DOM::DOMStringImpl;
69 using DOM::DoNotStayInBlock;
70 using DOM::DoNotUpdateLayout;
71 using DOM::EditingTextImpl;
72 using DOM::ElementImpl;
73 using DOM::EStayInBlock;
74 using DOM::HTMLElementImpl;
75 using DOM::HTMLImageElementImpl;
76 using DOM::NamedAttrMapImpl;
79 using DOM::NodeListImpl;
81 using DOM::PositionIterator;
84 using DOM::StayInBlock;
86 using DOM::TreeWalkerImpl;
89 #include "KWQAssertions.h"
90 #include "KWQLogging.h"
91 #include "KWQKHTMLPart.h"
95 #define ASSERT(assertion) ((void)0)
96 #define ASSERT_WITH_MESSAGE(assertion, formatAndArgs...) ((void)0)
97 #define ASSERT_NOT_REACHED() ((void)0)
98 #define LOG(channel, formatAndArgs...) ((void)0)
99 #define ERROR(formatAndArgs...) ((void)0)
100 #define ASSERT(assertion) assert(assertion)
102 #define debugPosition(a,b) ((void)0)
103 #define debugNode(a,b) ((void)0)
107 #define IF_IMPL_NULL_RETURN_ARG(arg) do { \
108 if (isNull()) { return arg; } \
111 #define IF_IMPL_NULL_RETURN do { \
112 if (isNull()) { return; } \
117 static inline bool isNBSP(const QChar &c)
119 return c == QChar(0xa0);
122 static inline bool isWS(const QChar &c)
124 return c.isSpace() && c != QChar(0xa0);
127 static inline bool isWS(const DOMString &text)
129 if (text.length() != 1)
132 return isWS(text[0]);
135 static inline bool isWS(const Position &pos)
140 if (!pos.node()->isTextNode())
143 const DOMString &string = static_cast<TextImpl *>(pos.node())->data();
144 return isWS(string[pos.offset()]);
147 static const int spacesPerTab = 4;
149 static inline bool isTab(const DOMString &text)
151 static QChar tabCharacter = QChar(0x9);
152 if (text.length() != 1)
155 return text[0] == tabCharacter;
158 static inline bool isTableStructureNode(const NodeImpl *node)
160 RenderObject *r = node->renderer();
161 return (r && (r->isTableCell() || r->isTableRow() || r->isTableSection() || r->isTableCol()));
164 static DOMString &nonBreakingSpaceString()
166 static DOMString nonBreakingSpaceString = QString(QChar(0xa0));
167 return nonBreakingSpaceString;
170 static DOMString &styleSpanClassString()
172 static DOMString styleSpanClassString = "khtml-style-span";
173 return styleSpanClassString;
176 static DOMString &blockPlaceholderClassString()
178 static DOMString blockPlaceholderClassString = "khtml-block-placeholder";
179 return blockPlaceholderClassString;
182 static void derefNodesInList(QPtrList<NodeImpl> &list)
184 for (QPtrListIterator<NodeImpl> it(list); it.current(); ++it)
185 it.current()->deref();
188 static void debugPosition(const char *prefix, const Position &pos)
193 LOG(Editing, "%s <null>", prefix);
195 LOG(Editing, "%s%s %p : %d", prefix, getTagName(pos.node()->id()).string().latin1(), pos.node(), pos.offset());
198 static void debugNode(const char *prefix, const NodeImpl *node)
203 LOG(Editing, "%s <null>", prefix);
205 LOG(Editing, "%s%s %p", prefix, getTagName(node->id()).string().latin1(), node);
208 //------------------------------------------------------------------------------------------
211 EditCommandPtr::EditCommandPtr()
215 EditCommandPtr::EditCommandPtr(EditCommand *impl) : SharedPtr<EditCommand>(impl)
219 EditCommandPtr::EditCommandPtr(const EditCommandPtr &o) : SharedPtr<EditCommand>(o)
223 EditCommandPtr::~EditCommandPtr()
227 EditCommandPtr &EditCommandPtr::operator=(const EditCommandPtr &c)
229 static_cast<SharedPtr<EditCommand> &>(*this) = c;
233 bool EditCommandPtr::isCompositeStep() const
235 IF_IMPL_NULL_RETURN_ARG(false);
236 return get()->isCompositeStep();
239 bool EditCommandPtr::isInsertTextCommand() const
241 IF_IMPL_NULL_RETURN_ARG(false);
242 return get()->isInsertTextCommand();
245 bool EditCommandPtr::isTypingCommand() const
247 IF_IMPL_NULL_RETURN_ARG(false);
248 return get()->isTypingCommand();
251 void EditCommandPtr::apply() const
257 void EditCommandPtr::unapply() const
263 void EditCommandPtr::reapply() const
269 HTMLEditAction EditCommandPtr::editingAction() const
271 IF_IMPL_NULL_RETURN_ARG(HTMLEditActionUnspecified);
272 return get()->editingAction();
275 DocumentImpl * const EditCommandPtr::document() const
277 IF_IMPL_NULL_RETURN_ARG(0);
278 return get()->document();
281 Selection EditCommandPtr::startingSelection() const
283 IF_IMPL_NULL_RETURN_ARG(Selection());
284 return get()->startingSelection();
287 Selection EditCommandPtr::endingSelection() const
289 IF_IMPL_NULL_RETURN_ARG(Selection());
290 return get()->endingSelection();
293 void EditCommandPtr::setStartingSelection(const Selection &s) const
296 get()->setStartingSelection(s);
299 void EditCommandPtr::setEndingSelection(const Selection &s) const
302 get()->setEndingSelection(s);
305 CSSMutableStyleDeclarationImpl *EditCommandPtr::typingStyle() const
307 IF_IMPL_NULL_RETURN_ARG(0);
308 return get()->typingStyle();
311 void EditCommandPtr::setTypingStyle(CSSMutableStyleDeclarationImpl *style) const
314 get()->setTypingStyle(style);
317 EditCommandPtr EditCommandPtr::parent() const
319 IF_IMPL_NULL_RETURN_ARG(0);
320 return get()->parent();
323 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
326 get()->setParent(cmd.get());
329 EditCommandPtr &EditCommandPtr::emptyCommand()
331 static EditCommandPtr m_emptyCommand;
332 return m_emptyCommand;
335 //------------------------------------------------------------------------------------------
338 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, ELegacyHTMLStyles usesLegacyStyles)
339 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
341 init(style, Position());
344 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
345 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
347 init(style, position);
350 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
353 CSSMutableStyleDeclarationImpl *mutableStyle = style->makeMutable();
357 QString styleText("");
359 QValueListConstIterator<CSSProperty> end;
360 for (QValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
361 const CSSProperty *property = &*it;
363 // If position is empty or the position passed in already has the
364 // style, just move on.
365 if (position.isNotNull() && currentlyHasStyle(position, property))
368 // If needed, figure out if this change is a legacy HTML style change.
369 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
373 styleText += property->cssText().string();
376 mutableStyle->deref();
378 // Save the result for later
379 m_cssStyle = styleText.stripWhiteSpace();
382 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
384 DOMString valueText(property->value()->cssText());
385 switch (property->id()) {
386 case CSS_PROP_FONT_WEIGHT:
387 if (strcasecmp(valueText, "bold") == 0) {
392 case CSS_PROP_FONT_STYLE:
393 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
394 m_applyItalic = true;
402 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
404 ASSERT(pos.isNotNull());
405 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
408 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
413 bool result = strcasecmp(value->cssText(), property->value()->cssText()) == 0;
418 //------------------------------------------------------------------------------------------
421 EditCommand::EditCommand(DocumentImpl *document)
422 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
425 ASSERT(m_document->part());
427 m_startingSelection = m_document->part()->selection();
428 m_endingSelection = m_startingSelection;
430 m_document->part()->setSelection(Selection(), false, true);
433 EditCommand::~EditCommand()
438 m_typingStyle->deref();
441 void EditCommand::apply()
444 ASSERT(m_document->part());
445 ASSERT(state() == NotApplied);
447 KHTMLPart *part = m_document->part();
449 ASSERT(part->selection().isNone());
455 // FIXME: Improve typing style.
456 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
457 if (!preservesTypingStyle())
460 if (!isCompositeStep()) {
461 document()->updateLayout();
462 EditCommandPtr cmd(this);
463 part->appliedEditing(cmd);
467 void EditCommand::unapply()
470 ASSERT(m_document->part());
471 ASSERT(state() == Applied);
473 bool topLevel = !isCompositeStep();
475 KHTMLPart *part = m_document->part();
478 part->setSelection(Selection(), false, true);
480 ASSERT(part->selection().isNone());
484 m_state = NotApplied;
487 document()->updateLayout();
488 EditCommandPtr cmd(this);
489 part->unappliedEditing(cmd);
493 void EditCommand::reapply()
496 ASSERT(m_document->part());
497 ASSERT(state() == NotApplied);
499 bool topLevel = !isCompositeStep();
501 KHTMLPart *part = m_document->part();
504 part->setSelection(Selection(), false, true);
506 ASSERT(part->selection().isNone());
513 document()->updateLayout();
514 EditCommandPtr cmd(this);
515 part->reappliedEditing(cmd);
519 void EditCommand::doReapply()
524 HTMLEditAction EditCommand::editingAction() const
526 return HTMLEditActionUnspecified;
529 void EditCommand::setStartingSelection(const Selection &s)
531 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
532 cmd->m_startingSelection = s;
535 void EditCommand::setEndingSelection(const Selection &s)
537 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
538 cmd->m_endingSelection = s;
541 void EditCommand::assignTypingStyle(CSSMutableStyleDeclarationImpl *style)
543 if (m_typingStyle == style)
546 CSSMutableStyleDeclarationImpl *old = m_typingStyle;
547 m_typingStyle = style;
549 m_typingStyle->ref();
554 void EditCommand::setTypingStyle(CSSMutableStyleDeclarationImpl *style)
556 // FIXME: Improve typing style.
557 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
558 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
559 cmd->assignTypingStyle(style);
562 bool EditCommand::preservesTypingStyle() const
567 bool EditCommand::isInsertTextCommand() const
572 bool EditCommand::isTypingCommand() const
577 //------------------------------------------------------------------------------------------
578 // CompositeEditCommand
580 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
581 : EditCommand(document)
585 void CompositeEditCommand::doUnapply()
587 if (m_cmds.count() == 0) {
591 for (int i = m_cmds.count() - 1; i >= 0; --i)
592 m_cmds[i]->unapply();
594 setState(NotApplied);
597 void CompositeEditCommand::doReapply()
599 if (m_cmds.count() == 0) {
603 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
610 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
612 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
614 cmd.setStartingSelection(endingSelection());
615 cmd.setEndingSelection(endingSelection());
621 void CompositeEditCommand::insertParagraphSeparator()
623 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
624 applyCommandToComposite(cmd);
627 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
629 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
630 applyCommandToComposite(cmd);
633 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
635 if (refChild->parentNode()->lastChild() == refChild) {
636 appendNode(insertChild, refChild->parentNode());
639 ASSERT(refChild->nextSibling());
640 insertNodeBefore(insertChild, refChild->nextSibling());
644 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
646 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
647 NodeImpl *child = refChild->firstChild();
648 for (long i = 0; child && i < offset; i++)
649 child = child->nextSibling();
651 insertNodeBefore(insertChild, child);
653 appendNode(insertChild, refChild);
655 else if (refChild->caretMinOffset() >= offset) {
656 insertNodeBefore(insertChild, refChild);
658 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
659 splitTextNode(static_cast<TextImpl *>(refChild), offset);
660 insertNodeBefore(insertChild, refChild);
663 insertNodeAfter(insertChild, refChild);
667 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
669 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
670 applyCommandToComposite(cmd);
673 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
675 if (isTableStructureNode(node)) {
676 // Do not remove an element of table structure; remove its contents.
677 NodeImpl *child = node->firstChild();
679 NodeImpl *remove = child;
680 child = child->nextSibling();
681 removeFullySelectedNode(remove);
685 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
686 applyCommandToComposite(cmd);
690 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
692 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
693 applyCommandToComposite(cmd);
696 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
698 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
699 applyCommandToComposite(cmd);
702 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
704 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
705 applyCommandToComposite(cmd);
708 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
710 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
711 applyCommandToComposite(cmd);
714 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
716 InsertTextCommand *impl = new InsertTextCommand(document());
717 EditCommandPtr cmd(impl);
718 applyCommandToComposite(cmd);
719 impl->input(text, selectInsertedText);
722 void CompositeEditCommand::insertTextIntoNode(TextImpl *node, long offset, const DOMString &text)
724 EditCommandPtr cmd(new InsertIntoTextNode(document(), node, offset, text));
725 applyCommandToComposite(cmd);
728 void CompositeEditCommand::deleteTextFromNode(TextImpl *node, long offset, long count)
730 EditCommandPtr cmd(new DeleteFromTextNodeCommand(document(), node, offset, count));
731 applyCommandToComposite(cmd);
734 void CompositeEditCommand::replaceTextInNode(TextImpl *node, long offset, long count, const DOMString &replacementText)
736 EditCommandPtr deleteCommand(new DeleteFromTextNodeCommand(document(), node, offset, count));
737 applyCommandToComposite(deleteCommand);
738 EditCommandPtr insertCommand(new InsertIntoTextNode(document(), node, offset, replacementText));
739 applyCommandToComposite(insertCommand);
742 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
744 if (endingSelection().isRange()) {
745 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
746 applyCommandToComposite(cmd);
750 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
752 if (selection.isRange()) {
753 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
754 applyCommandToComposite(cmd);
758 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
760 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
761 applyCommandToComposite(cmd);
764 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
766 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
767 applyCommandToComposite(cmd);
770 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
772 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
773 applyCommandToComposite(cmd);
776 void CompositeEditCommand::rebalanceWhitespace()
778 Selection selection = endingSelection();
779 if (selection.isCaretOrRange()) {
780 EditCommandPtr startCmd(new RebalanceWhitespaceCommand(document(), endingSelection().start()));
781 applyCommandToComposite(startCmd);
782 if (selection.isRange()) {
783 EditCommandPtr endCmd(new RebalanceWhitespaceCommand(document(), endingSelection().end()));
784 applyCommandToComposite(endCmd);
789 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
791 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
792 // and ApplyStyleCommand::computeStyleChange.
793 // Both function do similar work, and the common parts could be factored out.
795 // FIXME: Improve typing style.
796 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
798 // update document layout once before running the rest of the function
799 // so that we avoid the expense of updating before each and every call
800 // to check a computed style
801 document()->updateLayout();
803 StyleChange styleChange(document()->part()->typingStyle());
805 NodeImpl *childToAppend = child;
806 int exceptionCode = 0;
808 if (styleChange.applyItalic()) {
809 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
810 ASSERT(exceptionCode == 0);
811 italicElement->appendChild(childToAppend, exceptionCode);
812 ASSERT(exceptionCode == 0);
813 childToAppend = italicElement;
816 if (styleChange.applyBold()) {
817 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
818 ASSERT(exceptionCode == 0);
819 boldElement->appendChild(childToAppend, exceptionCode);
820 ASSERT(exceptionCode == 0);
821 childToAppend = boldElement;
824 if (styleChange.cssStyle().length() > 0) {
825 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
826 ASSERT(exceptionCode == 0);
827 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
828 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
829 styleElement->appendChild(childToAppend, exceptionCode);
830 ASSERT(exceptionCode == 0);
831 childToAppend = styleElement;
834 return childToAppend;
837 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
839 if (!textNode || !textNode->renderer() || start >= end)
842 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
843 InlineTextBox *box = textRenderer->firstTextBox();
845 // whole text node is empty
846 removeNode(textNode);
850 long length = textNode->length();
851 if (start >= length || end > length)
855 InlineTextBox *prevBox = 0;
856 DOMStringImpl *str = 0;
858 // This loop structure works to process all gaps preceding a box,
859 // and also will look at the gap after the last box.
860 while (prevBox || box) {
861 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
863 // No more chance for any intersections
866 int gapEnd = box ? box->m_start : length;
867 bool indicesIntersect = start <= gapEnd && end >= gapStart;
868 int gapLen = gapEnd - gapStart;
869 if (indicesIntersect && gapLen > 0) {
870 gapStart = kMax(gapStart, start);
871 gapEnd = kMin(gapEnd, end);
873 str = textNode->string()->substring(start, end - start);
876 // remove text in the gap
877 str->remove(gapStart - start - removed, gapLen);
883 box = box->nextTextBox();
887 // Replace the text between start and end with our pruned version.
889 replaceTextInNode(textNode, start, end - start, str);
892 // Assert that we are not going to delete all of the text in the node.
893 // If we were, that should have been done above with the call to
894 // removeNode and return.
895 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
896 deleteTextFromNode(textNode, start, end - start);
902 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
904 if (start.isNull() || end.isNull())
907 if (RangeImpl::compareBoundaryPoints(start, end) >= 0)
910 NodeImpl *node = start.node();
912 NodeImpl *next = node->traverseNextNode();
914 if (node->isTextNode()) {
915 TextImpl *textNode = static_cast<TextImpl *>(node);
916 bool isStartNode = node == start.node();
917 bool isEndNode = node == end.node();
918 int startOffset = isStartNode ? start.offset() : 0;
919 int endOffset = isEndNode ? end.offset() : textNode->length();
920 deleteInsignificantText(textNode, startOffset, endOffset);
923 if (node == end.node())
929 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
931 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
932 deleteInsignificantText(pos, end);
935 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
937 document()->updateLayout();
939 RenderObject *renderer = node->renderer();
940 if (!renderer->isBlockFlow())
943 if (renderer->height() > 0)
946 int exceptionCode = 0;
947 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
948 ASSERT(exceptionCode == 0);
949 breakNode->setAttribute(ATTR_CLASS, blockPlaceholderClassString());
950 appendNode(breakNode, node);
953 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
955 document()->updateLayout();
957 RenderObject *renderer = node->renderer();
958 if (!renderer->isBlockFlow())
961 // This code will remove a block placeholder if it still is at the end
962 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
963 // Of course, a person who hand-edits an HTML file could move a
964 // placeholder around, but it seems OK to be unconcerned about that case.
965 NodeImpl *last = node->lastChild();
966 if (last && last->isHTMLElement()) {
967 ElementImpl *element = static_cast<ElementImpl *>(last);
968 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
976 //==========================================================================================
978 //------------------------------------------------------------------------------------------
981 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
982 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
984 ASSERT(m_appendChild);
985 m_appendChild->ref();
987 ASSERT(m_parentNode);
991 AppendNodeCommand::~AppendNodeCommand()
993 ASSERT(m_appendChild);
994 m_appendChild->deref();
996 ASSERT(m_parentNode);
997 m_parentNode->deref();
1000 void AppendNodeCommand::doApply()
1002 ASSERT(m_appendChild);
1003 ASSERT(m_parentNode);
1005 int exceptionCode = 0;
1006 m_parentNode->appendChild(m_appendChild, exceptionCode);
1007 ASSERT(exceptionCode == 0);
1010 void AppendNodeCommand::doUnapply()
1012 ASSERT(m_appendChild);
1013 ASSERT(m_parentNode);
1014 ASSERT(state() == Applied);
1016 int exceptionCode = 0;
1017 m_parentNode->removeChild(m_appendChild, exceptionCode);
1018 ASSERT(exceptionCode == 0);
1021 //------------------------------------------------------------------------------------------
1022 // ApplyStyleCommand
1024 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style)
1025 : CompositeEditCommand(document), m_style(style->makeMutable())
1031 ApplyStyleCommand::~ApplyStyleCommand()
1037 void ApplyStyleCommand::doApply()
1039 // apply the block-centric properties of the style
1040 CSSMutableStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
1042 applyBlockStyle(blockStyle);
1044 // apply any remaining styles to the inline elements
1045 // NOTE: hopefully, this string comparison is the same as checking for a non-null diff
1046 if (blockStyle->length() < m_style->length()) {
1047 CSSMutableStyleDeclarationImpl *inlineStyle = m_style->copy();
1049 blockStyle->diff(inlineStyle);
1050 applyInlineStyle(inlineStyle);
1051 inlineStyle->deref();
1054 blockStyle->deref();
1056 setEndingSelectionNeedsLayout();
1059 void ApplyStyleCommand::applyBlockStyle(CSSMutableStyleDeclarationImpl *style)
1061 // update document layout once before removing styles
1062 // so that we avoid the expense of updating before each and every call
1063 // to check a computed style
1064 document()->updateLayout();
1066 // get positions we want to use for applying style
1067 Position start(endingSelection().start());
1068 Position end(endingSelection().end());
1070 // remove current values, if any, of the specified styles from the blocks
1071 // NOTE: tracks the previous block to avoid repeated processing
1072 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1073 NodeImpl *prevBlock = 0;
1074 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1075 NodeImpl *block = node->enclosingBlockFlowElement();
1076 if (block != prevBlock && block->isHTMLElement()) {
1077 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1082 // apply specified styles to the block flow elements in the selected range
1084 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1085 NodeImpl *block = node->enclosingBlockFlowElement();
1086 if (block != prevBlock && block->isHTMLElement()) {
1087 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1093 void ApplyStyleCommand::applyInlineStyle(CSSMutableStyleDeclarationImpl *style)
1095 // adjust to the positions we want to use for applying style
1096 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1097 Position end(endingSelection().end().upstream(StayInBlock));
1099 // update document layout once before removing styles
1100 // so that we avoid the expense of updating before each and every call
1101 // to check a computed style
1102 document()->updateLayout();
1104 // Remove style from the selection.
1105 // Use the upstream position of the start for removing style.
1106 // This will ensure we remove all traces of the relevant styles from the selection
1107 // and prevent us from adding redundant ones, as described in:
1108 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1109 removeInlineStyle(style, start.upstream(), end);
1111 // split the start node if the selection starts inside of it
1112 bool splitStart = splitTextAtStartIfNeeded(start, end);
1114 start = endingSelection().start();
1115 end = endingSelection().end();
1118 // split the end node if the selection ends inside of it
1119 splitTextAtEndIfNeeded(start, end);
1120 start = endingSelection().start();
1121 end = endingSelection().end();
1123 // update document layout once before running the rest of the function
1124 // so that we avoid the expense of updating before each and every call
1125 // to check a computed style
1126 document()->updateLayout();
1128 if (start.node() == end.node()) {
1129 // simple case...start and end are the same node
1130 addInlineStyleIfNeeded(style, start.node(), end.node());
1133 NodeImpl *node = start.node();
1135 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1136 NodeImpl *runStart = node;
1138 NodeImpl *next = node->traverseNextNode();
1139 // Break if node is the end node, or if the next node does not fit in with
1140 // the current group.
1141 if (node == end.node() ||
1142 runStart->parentNode() != next->parentNode() ||
1143 (next->isHTMLElement() && next->id() != ID_BR) ||
1144 (next->renderer() && !next->renderer()->isInline()))
1148 // Now apply style to the run we found.
1149 addInlineStyleIfNeeded(style, runStart, node);
1151 if (node == end.node())
1153 node = node->traverseNextNode();
1158 //------------------------------------------------------------------------------------------
1159 // ApplyStyleCommand: style-removal helpers
1161 bool ApplyStyleCommand::isHTMLStyleNode(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1163 QValueListConstIterator<CSSProperty> end;
1164 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1165 switch ((*it).id()) {
1166 case CSS_PROP_FONT_WEIGHT:
1167 if (elem->id() == ID_B)
1170 case CSS_PROP_FONT_STYLE:
1171 if (elem->id() == ID_I)
1180 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1182 // This node can be removed.
1183 // EDIT FIXME: This does not handle the case where the node
1184 // has attributes. But how often do people add attributes to <B> tags?
1185 // Not so often I think.
1187 removeNodePreservingChildren(elem);
1190 void ApplyStyleCommand::removeCSSStyle(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1195 CSSMutableStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1199 QValueListConstIterator<CSSProperty> end;
1200 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1201 int propertyID = (*it).id();
1202 CSSValueImpl *value = decl->getPropertyCSSValue(propertyID);
1205 removeCSSProperty(decl, propertyID);
1210 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1211 // Check to see if the span is one we added to apply style.
1212 // If it is, and there are no more attributes on the span other than our
1213 // class marker, remove the span.
1214 if (decl->length() == 0) {
1215 removeNodeAttribute(elem, ATTR_STYLE);
1216 NamedAttrMapImpl *map = elem->attributes();
1217 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1218 removeNodePreservingChildren(elem);
1223 void ApplyStyleCommand::removeBlockStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1225 ASSERT(start.isNotNull());
1226 ASSERT(end.isNotNull());
1227 ASSERT(start.node()->inDocument());
1228 ASSERT(end.node()->inDocument());
1229 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1233 void ApplyStyleCommand::removeInlineStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1235 ASSERT(start.isNotNull());
1236 ASSERT(end.isNotNull());
1237 ASSERT(start.node()->inDocument());
1238 ASSERT(end.node()->inDocument());
1239 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1241 NodeImpl *node = start.node();
1243 NodeImpl *next = node->traverseNextNode();
1244 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1245 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1246 if (isHTMLStyleNode(style, elem))
1247 removeHTMLStyleNode(elem);
1249 removeCSSStyle(style, elem);
1251 if (node == end.node())
1257 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1261 Position pos = Position(node, node->childNodeCount()).upstream();
1262 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1263 RangeImpl::compareBoundaryPoints(pos, end) <= 0;
1266 //------------------------------------------------------------------------------------------
1267 // ApplyStyleCommand: style-application helpers
1270 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1272 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1273 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1274 TextImpl *text = static_cast<TextImpl *>(start.node());
1275 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1276 applyCommandToComposite(cmd);
1277 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1283 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1285 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1286 TextImpl *text = static_cast<TextImpl *>(end.node());
1287 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1288 EditCommandPtr cmd(impl);
1289 applyCommandToComposite(cmd);
1290 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1292 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1293 return impl->node()->previousSibling();
1298 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1304 NodeImpl *node = startNode;
1306 NodeImpl *next = node->traverseNextNode();
1307 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1309 appendNode(node, element);
1311 if (node == endNode)
1317 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *block)
1319 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1321 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1322 if (styleChange.cssStyle().length() > 0) {
1323 DOMString cssText = styleChange.cssStyle();
1324 CSSMutableStyleDeclarationImpl *decl = block->inlineStyleDecl();
1326 cssText += decl->cssText();
1327 block->setAttribute(ATTR_STYLE, cssText);
1331 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1333 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1334 // Both functions do similar work, and the common parts could be factored out.
1336 StyleChange styleChange(style, Position(startNode, 0));
1337 int exceptionCode = 0;
1339 if (styleChange.cssStyle().length() > 0) {
1340 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1341 ASSERT(exceptionCode == 0);
1342 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1343 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1344 insertNodeBefore(styleElement, startNode);
1345 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1348 if (styleChange.applyBold()) {
1349 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1350 ASSERT(exceptionCode == 0);
1351 insertNodeBefore(boldElement, startNode);
1352 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1355 if (styleChange.applyItalic()) {
1356 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1357 ASSERT(exceptionCode == 0);
1358 insertNodeBefore(italicElement, startNode);
1359 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1363 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1365 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1366 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1367 EditCommandPtr split(impl);
1369 pos = Position(impl->node(), 0);
1373 // EDIT FIXME: If modified to work with the internals of applying style,
1374 // this code can work to optimize cases where a style change is taking place on
1375 // a boundary between nodes where one of the nodes has the desired style. In other
1376 // words, it is possible for content to be merged into existing nodes rather than adding
1377 // additional markup.
1378 if (currentlyHasStyle(pos))
1382 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1383 NodeImpl *nextNode = pos.node()->traverseNextNode();
1385 Position next = Position(nextNode, 0);
1386 if (currentlyHasStyle(next))
1391 // try previous node
1392 if (pos.offset() <= pos.node()->caretMinOffset()) {
1393 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1395 Position prev = Position(prevNode, prevNode->maxOffset());
1396 if (currentlyHasStyle(prev))
1405 //------------------------------------------------------------------------------------------
1406 // DeleteFromTextNodeCommand
1408 DeleteFromTextNodeCommand::DeleteFromTextNodeCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1409 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1412 ASSERT(m_offset >= 0);
1413 ASSERT(m_offset < (long)m_node->length());
1414 ASSERT(m_count >= 0);
1419 DeleteFromTextNodeCommand::~DeleteFromTextNodeCommand()
1425 void DeleteFromTextNodeCommand::doApply()
1429 int exceptionCode = 0;
1430 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1431 ASSERT(exceptionCode == 0);
1433 m_node->deleteData(m_offset, m_count, exceptionCode);
1434 ASSERT(exceptionCode == 0);
1437 void DeleteFromTextNodeCommand::doUnapply()
1440 ASSERT(!m_text.isEmpty());
1442 int exceptionCode = 0;
1443 m_node->insertData(m_offset, m_text, exceptionCode);
1444 ASSERT(exceptionCode == 0);
1447 //------------------------------------------------------------------------------------------
1448 // DeleteSelectionCommand
1450 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1451 : CompositeEditCommand(document),
1452 m_hasSelectionToDelete(false),
1453 m_smartDelete(smartDelete),
1454 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1462 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1463 : CompositeEditCommand(document),
1464 m_hasSelectionToDelete(true),
1465 m_smartDelete(smartDelete),
1466 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1467 m_selectionToDelete(selection),
1475 void DeleteSelectionCommand::initializePositionData()
1478 // Handle setting some basic positions
1480 Position start = m_selectionToDelete.start();
1481 Position end = m_selectionToDelete.end();
1483 m_upstreamStart = start.upstream(StayInBlock);
1484 m_downstreamStart = start.downstream(StayInBlock);
1485 m_upstreamEnd = end.upstream(StayInBlock);
1486 m_downstreamEnd = end.downstream(StayInBlock);
1489 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
1491 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1492 bool hasLeadingWhitespaceBeforeAdjustment = m_leadingWhitespace.isNotNull();
1493 if (m_smartDelete && hasLeadingWhitespaceBeforeAdjustment) {
1494 Position pos = VisiblePosition(start).previous().deepEquivalent();
1495 // Expand out one character upstream for smart delete and recalculate
1496 // positions based on this change.
1497 m_upstreamStart = pos.upstream(StayInBlock);
1498 m_downstreamStart = pos.downstream(StayInBlock);
1499 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1501 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1502 // Note: trailing whitespace is only considered for smart delete if there is no leading
1503 // whitespace, as in the case where you double-click the first word of a paragraph.
1504 if (m_smartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_trailingWhitespace.isNotNull()) {
1505 // Expand out one character downstream for smart delete and recalculate
1506 // positions based on this change.
1507 Position pos = VisiblePosition(end).next().deepEquivalent();
1508 m_upstreamEnd = pos.upstream(StayInBlock);
1509 m_downstreamEnd = pos.downstream(StayInBlock);
1510 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1512 m_trailingWhitespaceValid = true;
1515 // Handle setting start and end blocks and the start node.
1517 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1518 m_startBlock->ref();
1519 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1521 m_startNode = m_upstreamStart.node();
1525 // Handle detecting if the line containing the selection end is itself fully selected.
1526 // This is one of the tests that determines if block merging of content needs to be done.
1528 VisiblePosition visibleEnd(end);
1529 if (isFirstVisiblePositionOnLine(visibleEnd)) {
1530 Position previousLineStart = previousLinePosition(visibleEnd, DOWNSTREAM, 0).deepEquivalent();
1531 if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
1532 m_mergeBlocksAfterDelete = false;
1535 debugPosition("m_upstreamStart ", m_upstreamStart);
1536 debugPosition("m_downstreamStart ", m_downstreamStart);
1537 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1538 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1539 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1540 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1541 debugNode( "m_startBlock ", m_startBlock);
1542 debugNode( "m_endBlock ", m_endBlock);
1543 debugNode( "m_startNode ", m_startNode);
1546 void DeleteSelectionCommand::saveTypingStyleState()
1548 // Figure out the typing style in effect before the delete is done.
1549 // FIXME: Improve typing style.
1550 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1551 CSSComputedStyleDeclarationImpl *computedStyle = m_selectionToDelete.start().computedStyle();
1552 computedStyle->ref();
1553 m_typingStyle = computedStyle->copyInheritableProperties();
1554 m_typingStyle->ref();
1555 computedStyle->deref();
1558 bool DeleteSelectionCommand::handleSpecialCaseAllContentDelete()
1560 Position start = m_downstreamStart;
1561 Position end = m_upstreamEnd;
1563 ElementImpl *rootElement = start.node()->rootEditableElement();
1564 Position rootStart = Position(rootElement, 0);
1565 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1566 if (start == VisiblePosition(rootStart).downstreamDeepEquivalent() && end == VisiblePosition(rootEnd).deepEquivalent()) {
1567 // Delete every child of the root editable element
1568 NodeImpl *node = rootElement->firstChild();
1570 NodeImpl *next = node->traverseNextSibling();
1579 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
1581 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1582 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1583 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1584 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1585 if (isBROnLineByItself) {
1586 removeNode(m_downstreamStart.node());
1587 m_endingPosition = m_upstreamStart;
1588 m_mergeBlocksAfterDelete = false;
1592 // Check for special-case where the selection contains only a BR right after a block ended.
1593 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1594 Position upstreamFromBR = m_downstreamEnd.upstream();
1595 Position downstreamFromStart = m_downstreamStart.downstream();
1596 bool startIsBRAfterBlock = downstreamEndIsBR && downstreamFromStart.node() == m_downstreamEnd.node() &&
1597 m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamFromBR.node()->enclosingBlockFlowElement();
1598 if (startIsBRAfterBlock) {
1599 removeNode(m_downstreamEnd.node());
1600 m_endingPosition = upstreamFromBR;
1601 m_mergeBlocksAfterDelete = false;
1605 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1606 // should not be done.
1607 if (upstreamStartIsBR && downstreamStartIsBR)
1608 m_mergeBlocksAfterDelete = false;
1613 void DeleteSelectionCommand::handleGeneralDelete()
1615 int startOffset = m_upstreamStart.offset();
1617 if (startOffset == 0 && m_startNode->isBlockFlow() && m_startBlock != m_endBlock && !m_endBlock->isAncestor(m_startBlock)) {
1618 // The block containing the start of the selection is completely selected.
1619 // Delete it all in one step right here.
1620 ASSERT(!m_downstreamEnd.node()->isAncestor(m_startNode));
1622 // shift the start node to the start of the next block.
1623 NodeImpl *old = m_startNode;
1624 m_startNode = m_startBlock->traverseNextSibling();
1629 removeFullySelectedNode(m_startBlock);
1631 else if (startOffset >= m_startNode->caretMaxOffset()) {
1632 // Move the start node to the next node in the tree since the startOffset is equal to
1633 // or beyond the start node's caretMaxOffset This means there is nothing visible to delete.
1634 // However, before moving on, delete any insignificant text that may be present in a text node.
1635 if (m_startNode->isTextNode()) {
1636 // Delete any insignificant text from this node.
1637 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1638 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1639 deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1642 // shift the start node to the next
1643 NodeImpl *old = m_startNode;
1644 m_startNode = old->traverseNextNode();
1650 if (m_startNode == m_downstreamEnd.node()) {
1651 // The selection to delete is all in one node.
1652 if (!m_startNode->renderer() ||
1653 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1655 removeFullySelectedNode(m_startNode);
1657 else if (m_downstreamEnd.offset() - startOffset > 0) {
1658 // in a text node that needs to be trimmed
1659 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1660 deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
1661 m_trailingWhitespaceValid = false;
1665 // The selection to delete spans more than one node.
1666 NodeImpl *node = m_startNode;
1668 if (startOffset > 0) {
1669 // in a text node that needs to be trimmed
1670 TextImpl *text = static_cast<TextImpl *>(node);
1671 deleteTextFromNode(text, startOffset, text->length() - startOffset);
1672 node = node->traverseNextNode();
1675 // handle deleting all nodes that are completely selected
1676 while (node && node != m_downstreamEnd.node()) {
1677 if (!m_downstreamEnd.node()->isAncestor(node)) {
1678 NodeImpl *nextNode = node->traverseNextSibling();
1679 removeFullySelectedNode(node);
1683 NodeImpl *n = node->lastChild();
1684 while (n && n->lastChild())
1686 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1687 // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
1688 removeFullySelectedNode(node);
1689 m_trailingWhitespaceValid = false;
1693 node = node->traverseNextNode();
1698 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1699 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1700 // need to delete whole node
1701 // we can get here if this is the last node in the block
1702 removeFullySelectedNode(m_downstreamEnd.node());
1703 m_trailingWhitespaceValid = false;
1706 // in a text node that needs to be trimmed
1707 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1708 if (m_downstreamEnd.offset() > 0) {
1709 deleteTextFromNode(text, 0, m_downstreamEnd.offset());
1710 m_downstreamEnd = Position(text, 0);
1711 m_trailingWhitespaceValid = false;
1718 void DeleteSelectionCommand::fixupWhitespace()
1720 document()->updateLayout();
1721 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1722 LOG(Editing, "replace leading");
1723 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1724 replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1726 else if (m_trailingWhitespace.isNotNull()) {
1727 if (m_trailingWhitespaceValid) {
1728 if (!m_trailingWhitespace.isRenderedCharacter()) {
1729 LOG(Editing, "replace trailing [valid]");
1730 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1731 replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1735 Position pos = m_endingPosition.downstream(StayInBlock);
1736 pos = Position(pos.node(), pos.offset() - 1);
1737 if (isWS(pos) && !pos.isRenderedCharacter()) {
1738 LOG(Editing, "replace trailing [invalid]");
1739 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1740 replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
1741 // need to adjust ending position since the trailing position is not valid.
1742 m_endingPosition = pos;
1748 // This function moves nodes in the block containing startNode to dstBlock, starting
1749 // from startNode and proceeding to the end of the block. Nodes in the block containing
1750 // startNode that appear in document order before startNode are not moved.
1751 // This function is an important helper for deleting selections that cross block
1753 void DeleteSelectionCommand::moveNodesAfterNode()
1755 if (!m_mergeBlocksAfterDelete)
1758 if (m_endBlock == m_startBlock)
1761 NodeImpl *startNode = m_downstreamEnd.node();
1762 NodeImpl *dstNode = m_upstreamStart.node();
1764 if (!startNode->inDocument() || !dstNode->inDocument())
1767 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1768 if (isTableStructureNode(startBlock))
1769 // Do not move content between parts of a table
1772 // Now that we are about to add content, check to see if a placeholder element
1774 removeBlockPlaceholderIfNeeded(startBlock);
1776 // Move the subtree containing node
1777 NodeImpl *node = startNode->enclosingInlineElement();
1779 // Insert after the subtree containing destNode
1780 NodeImpl *refNode = dstNode->enclosingInlineElement();
1782 // Nothing to do if start is already at the beginning of dstBlock
1783 NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
1784 if (startBlock == dstBlock->firstChild())
1788 while (node && node->isAncestor(startBlock)) {
1789 NodeImpl *moveNode = node;
1790 node = node->nextSibling();
1791 removeNode(moveNode);
1792 insertNodeAfter(moveNode, refNode);
1796 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1797 // to make the layout come out right. Consider this document:
1803 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1804 // move the contents of the div to the block containing 'One' and delete the div.
1805 // This will have the side effect of moving 'Three' on to the same line as 'One'
1806 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1807 // This may not be ideal, but it is better than nothing.
1808 document()->updateLayout();
1809 if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
1810 removeNode(startBlock);
1811 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1812 int exceptionCode = 0;
1813 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1814 ASSERT(exceptionCode == 0);
1815 insertNodeAfter(breakNode, refNode);
1820 void DeleteSelectionCommand::calculateEndingPosition()
1822 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1825 m_endingPosition = m_upstreamStart;
1826 if (m_endingPosition.node()->inDocument())
1829 m_endingPosition = m_downstreamEnd;
1830 if (m_endingPosition.node()->inDocument())
1833 m_endingPosition = Position(m_startBlock, 0);
1834 if (m_endingPosition.node()->inDocument())
1837 m_endingPosition = Position(m_endBlock, 0);
1838 if (m_endingPosition.node()->inDocument())
1841 m_endingPosition = Position(document()->documentElement(), 0);
1844 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1846 // Compute the difference between the style before the delete and the style now
1847 // after the delete has been done. Set this style on the part, so other editing
1848 // commands being composed with this one will work, and also cache it on the command,
1849 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1851 // FIXME: Improve typing style.
1852 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1853 if (m_startNode == m_endingPosition.node())
1854 document()->part()->setTypingStyle(0);
1856 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1857 endingStyle.diff(m_typingStyle);
1858 if (!m_typingStyle->length()) {
1859 m_typingStyle->deref();
1862 document()->part()->setTypingStyle(m_typingStyle);
1863 setTypingStyle(m_typingStyle);
1867 void DeleteSelectionCommand::clearTransientState()
1869 m_selectionToDelete.clear();
1870 m_upstreamStart.clear();
1871 m_downstreamStart.clear();
1872 m_upstreamEnd.clear();
1873 m_downstreamEnd.clear();
1874 m_endingPosition.clear();
1875 m_leadingWhitespace.clear();
1876 m_trailingWhitespace.clear();
1879 m_startBlock->deref();
1883 m_endBlock->deref();
1887 m_startNode->deref();
1890 if (m_typingStyle) {
1891 m_typingStyle->deref();
1896 void DeleteSelectionCommand::doApply()
1898 // If selection has not been set to a custom selection when the command was created,
1899 // use the current ending selection.
1900 if (!m_hasSelectionToDelete)
1901 m_selectionToDelete = endingSelection();
1903 if (!m_selectionToDelete.isRange())
1906 initializePositionData();
1908 if (!m_startBlock || !m_endBlock) {
1909 // Can't figure out what blocks we're in. This can happen if
1910 // the document structure is not what we are expecting, like if
1911 // the document has no body element, or if the editable block
1912 // has been changed to display: inline. Some day it might
1913 // be nice to be able to deal with this, but for now, bail.
1914 clearTransientState();
1918 // Delete any text that may hinder our ability to fixup whitespace after the detele
1919 deleteInsignificantTextDownstream(m_trailingWhitespace);
1921 saveTypingStyleState();
1923 if (!handleSpecialCaseAllContentDelete())
1924 if (!handleSpecialCaseBRDelete())
1925 handleGeneralDelete();
1927 // Do block merge if start and end of selection are in different blocks.
1928 moveNodesAfterNode();
1930 calculateEndingPosition();
1933 // If the delete emptied a block, add in a placeholder so the block does not
1934 // seem to disappear.
1935 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1936 calculateTypingStyleAfterDelete();
1937 setEndingSelection(m_endingPosition);
1938 debugPosition("endingPosition ", m_endingPosition);
1939 clearTransientState();
1940 rebalanceWhitespace();
1943 bool DeleteSelectionCommand::preservesTypingStyle() const
1948 //------------------------------------------------------------------------------------------
1949 // InsertIntoTextNode
1951 InsertIntoTextNode::InsertIntoTextNode(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
1952 : EditCommand(document), m_node(node), m_offset(offset)
1955 ASSERT(m_offset >= 0);
1956 ASSERT(!text.isEmpty());
1959 m_text = text.copy(); // make a copy to ensure that the string never changes
1962 InsertIntoTextNode::~InsertIntoTextNode()
1968 void InsertIntoTextNode::doApply()
1971 ASSERT(m_offset >= 0);
1972 ASSERT(!m_text.isEmpty());
1974 int exceptionCode = 0;
1975 m_node->insertData(m_offset, m_text, exceptionCode);
1976 ASSERT(exceptionCode == 0);
1979 void InsertIntoTextNode::doUnapply()
1982 ASSERT(m_offset >= 0);
1983 ASSERT(!m_text.isEmpty());
1985 int exceptionCode = 0;
1986 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
1987 ASSERT(exceptionCode == 0);
1990 //------------------------------------------------------------------------------------------
1991 // InsertLineBreakCommand
1993 InsertLineBreakCommand::InsertLineBreakCommand(DocumentImpl *document)
1994 : CompositeEditCommand(document)
1998 void InsertLineBreakCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
2000 // Insert the BR after the caret position. In the case the
2001 // position is a block, do an append. We don't want to insert
2002 // the BR *after* the block.
2003 Position upstream(pos.upstream(StayInBlock));
2004 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2005 if (cb == pos.node())
2006 appendNode(node, cb);
2008 insertNodeAfter(node, pos.node());
2011 void InsertLineBreakCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
2013 // Insert the BR after the caret position. In the case the
2014 // position is a block, do an append. We don't want to insert
2015 // the BR *before* the block.
2016 Position upstream(pos.upstream(StayInBlock));
2017 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2018 if (cb == pos.node())
2019 appendNode(node, cb);
2021 insertNodeBefore(node, pos.node());
2024 void InsertLineBreakCommand::doApply()
2027 Selection selection = endingSelection();
2029 int exceptionCode = 0;
2030 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
2031 ASSERT(exceptionCode == 0);
2033 NodeImpl *nodeToInsert = breakNode;
2035 // Handle the case where there is a typing style.
2036 // FIXME: Improve typing style.
2037 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2038 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2039 if (typingStyle && typingStyle->length() > 0)
2040 nodeToInsert = applyTypingStyle(breakNode);
2042 Position pos(selection.start().upstream(StayInBlock));
2043 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
2044 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
2045 bool atEndOfBlock = isLastVisiblePositionInBlock(VisiblePosition(pos));
2048 LOG(Editing, "input newline case 1");
2049 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
2050 // This makes the "real" BR we want to insert appear in the rendering without any
2051 // significant side effects (and no real worries either since you can't arrow past
2053 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
2054 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
2055 insertNodeBefore(nodeToInsert, pos.node());
2058 NodeImpl *next = pos.node()->traverseNextNode();
2059 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
2060 insertNodeAfterPosition(nodeToInsert, pos);
2061 if (hasTrailingBR) {
2062 setEndingSelection(Position(next, 0));
2064 else if (!document()->inStrictMode()) {
2065 // Insert an "extra" BR at the end of the block.
2066 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
2067 ASSERT(exceptionCode == 0);
2068 insertNodeAfter(extraBreakNode, nodeToInsert);
2069 setEndingSelection(Position(extraBreakNode, 0));
2074 LOG(Editing, "input newline case 2");
2075 // Insert node before downstream position, and place caret there as well.
2076 Position endingPosition = pos.downstream(StayInBlock);
2077 insertNodeBeforePosition(nodeToInsert, endingPosition);
2078 setEndingSelection(endingPosition);
2081 LOG(Editing, "input newline case 3");
2082 // Insert BR after this node. Place caret in the position that is downstream
2083 // of the current position, reckoned before inserting the BR in between.
2084 Position endingPosition = pos.downstream(StayInBlock);
2085 insertNodeAfterPosition(nodeToInsert, pos);
2086 setEndingSelection(endingPosition);
2089 // Split a text node
2090 LOG(Editing, "input newline case 4");
2091 ASSERT(pos.node()->isTextNode());
2094 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2095 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
2096 deleteTextFromNode(textNode, 0, pos.offset());
2097 insertNodeBefore(textBeforeNode, textNode);
2098 insertNodeBefore(nodeToInsert, textNode);
2099 Position endingPosition = Position(textNode, 0);
2101 // Handle whitespace that occurs after the split
2102 document()->updateLayout();
2103 if (!endingPosition.isRenderedCharacter()) {
2104 // Clear out all whitespace and insert one non-breaking space
2105 deleteInsignificantTextDownstream(endingPosition);
2106 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
2109 setEndingSelection(endingPosition);
2111 rebalanceWhitespace();
2114 //------------------------------------------------------------------------------------------
2115 // InsertNodeBeforeCommand
2117 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2118 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2120 ASSERT(m_insertChild);
2121 m_insertChild->ref();
2127 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2129 ASSERT(m_insertChild);
2130 m_insertChild->deref();
2133 m_refChild->deref();
2136 void InsertNodeBeforeCommand::doApply()
2138 ASSERT(m_insertChild);
2140 ASSERT(m_refChild->parentNode());
2142 int exceptionCode = 0;
2143 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2144 ASSERT(exceptionCode == 0);
2147 void InsertNodeBeforeCommand::doUnapply()
2149 ASSERT(m_insertChild);
2151 ASSERT(m_refChild->parentNode());
2153 int exceptionCode = 0;
2154 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2155 ASSERT(exceptionCode == 0);
2158 //------------------------------------------------------------------------------------------
2159 // InsertParagraphSeparatorCommand
2161 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(DocumentImpl *document)
2162 : CompositeEditCommand(document)
2166 InsertParagraphSeparatorCommand::~InsertParagraphSeparatorCommand()
2168 derefNodesInList(clonedNodes);
2171 ElementImpl *InsertParagraphSeparatorCommand::createParagraphElement()
2173 static DOMString paragraphStyle("margin-top: 0.1em; margin-bottom: 0.1em");
2175 int exceptionCode = 0;
2176 ElementImpl *element = document()->createHTMLElement("p", exceptionCode);
2177 ASSERT(exceptionCode == 0);
2178 element->setAttribute(ATTR_STYLE, paragraphStyle);
2180 clonedNodes.append(element);
2184 void InsertParagraphSeparatorCommand::doApply()
2186 Selection selection = endingSelection();
2187 if (selection.isNone())
2190 // Delete the current selection.
2191 // If the selection is a range and the start and end nodes are in different blocks,
2192 // then this command bails after the delete, but takes the one additional step of
2193 // moving the selection downstream so it is in the ending block (if that block is
2194 // still around, that is).
2195 Position pos = selection.start();
2196 if (selection.isRange()) {
2197 NodeImpl *startBlockBeforeDelete = selection.start().node()->enclosingBlockFlowElement();
2198 NodeImpl *endBlockBeforeDelete = selection.end().node()->enclosingBlockFlowElement();
2199 bool doneAfterDelete = startBlockBeforeDelete != endBlockBeforeDelete;
2200 deleteSelection(false, false);
2201 if (doneAfterDelete) {
2202 document()->updateLayout();
2203 setEndingSelection(endingSelection().start().downstream());
2204 rebalanceWhitespace();
2207 pos = endingSelection().start().upstream();
2210 // Find the start block.
2211 NodeImpl *startNode = pos.node();
2212 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
2213 if (!startBlock || !startBlock->parentNode())
2216 // Build up list of ancestors in between the start node and the start block.
2217 if (startNode != startBlock) {
2218 for (NodeImpl *n = startNode->parentNode(); n && n != startBlock; n = n->parentNode())
2219 ancestors.prepend(n);
2222 // Make new block to represent the newline.
2223 // If the start block is the body, just make a P tag, otherwise, make a shallow clone
2224 // of the the start block.
2225 NodeImpl *addedBlock = 0;
2226 if (startBlock == startBlock->rootEditableElement()) {
2227 if (startBlock->renderer() && !startBlock->renderer()->firstChild()) {
2228 // No rendered kids in the root editable element.
2229 // Just inserting a <p> in this situation is not enough, since this operation
2230 // is supposed to add an additional user-visible line to the content.
2231 // So, insert an extra <p> to make the one we insert right appear as the second
2232 // line in the root editable element.
2233 NodeImpl *extraBlock = createParagraphElement();
2234 appendNode(extraBlock, startBlock);
2235 insertBlockPlaceholderIfNeeded(extraBlock);
2237 addedBlock = createParagraphElement();
2238 appendNode(addedBlock, startBlock);
2241 addedBlock = startBlock->cloneNode(false);
2242 insertNodeAfter(addedBlock, startBlock);
2245 insertBlockPlaceholderIfNeeded(addedBlock);
2246 clonedNodes.append(addedBlock);
2248 if (!isLastVisiblePositionInNode(VisiblePosition(pos), startBlock)) {
2249 // Split at pos if in the middle of a text node.
2250 if (startNode->isTextNode()) {
2251 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2252 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2253 if (pos.offset() > 0 && !atEnd) {
2254 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2255 EditCommandPtr cmd(splitCommand);
2256 applyCommandToComposite(cmd);
2257 startNode = splitCommand->node();
2258 pos = Position(startNode, 0);
2261 startNode = startNode->traverseNextNode();
2265 else if (pos.offset() > 0) {
2266 startNode = startNode->traverseNextNode();
2270 // Make clones of ancestors in between the start node and the start block.
2271 NodeImpl *parent = addedBlock;
2272 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2273 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2275 clonedNodes.append(child);
2276 appendNode(child, parent);
2280 // Move the start node and the siblings of the start node.
2281 if (startNode != startBlock) {
2282 NodeImpl *n = startNode;
2283 if (n->id() == ID_BR)
2284 n = n->nextSibling();
2285 while (n && n != addedBlock) {
2286 NodeImpl *next = n->nextSibling();
2288 appendNode(n, parent);
2293 // Move everything after the start node.
2294 NodeImpl *leftParent = ancestors.last();
2295 while (leftParent && leftParent != startBlock) {
2296 parent = parent->parentNode();
2297 NodeImpl *n = leftParent->nextSibling();
2299 NodeImpl *next = n->nextSibling();
2301 appendNode(n, parent);
2304 leftParent = leftParent->parentNode();
2308 // Put the selection right at the start of the added block.
2309 setEndingSelection(Position(addedBlock, 0));
2310 rebalanceWhitespace();
2313 //------------------------------------------------------------------------------------------
2314 // InsertParagraphSeparatorInQuotedContentCommand
2316 InsertParagraphSeparatorInQuotedContentCommand::InsertParagraphSeparatorInQuotedContentCommand(DocumentImpl *document)
2317 : CompositeEditCommand(document)
2321 InsertParagraphSeparatorInQuotedContentCommand::~InsertParagraphSeparatorInQuotedContentCommand()
2323 derefNodesInList(clonedNodes);
2325 m_breakNode->deref();
2328 bool InsertParagraphSeparatorInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
2330 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
2333 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
2336 void InsertParagraphSeparatorInQuotedContentCommand::doApply()
2338 Selection selection = endingSelection();
2339 if (selection.isNone())
2342 // Delete the current selection.
2343 Position pos = selection.start();
2344 if (selection.isRange()) {
2345 deleteSelection(false, false);
2346 pos = endingSelection().start().upstream();
2349 // Find the top-most blockquote from the start.
2350 NodeImpl *startNode = pos.node();
2351 NodeImpl *topBlockquote = 0;
2352 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
2353 if (isMailBlockquote(n))
2356 if (!topBlockquote || !topBlockquote->parentNode())
2359 // Build up list of ancestors in between the start node and the top blockquote.
2360 if (startNode != topBlockquote) {
2361 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
2362 ancestors.prepend(n);
2365 // Insert a break after the top blockquote.
2366 int exceptionCode = 0;
2367 m_breakNode = document()->createHTMLElement("BR", exceptionCode);
2369 ASSERT(exceptionCode == 0);
2370 insertNodeAfter(m_breakNode, topBlockquote);
2372 if (!isLastVisiblePositionInNode(VisiblePosition(pos), topBlockquote)) {
2373 // Split at pos if in the middle of a text node.
2374 if (startNode->isTextNode()) {
2375 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2376 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2377 if (pos.offset() > 0 && !atEnd) {
2378 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2379 EditCommandPtr cmd(splitCommand);
2380 applyCommandToComposite(cmd);
2381 startNode = splitCommand->node();
2382 pos = Position(startNode, 0);
2385 startNode = startNode->traverseNextNode();
2389 else if (pos.offset() > 0) {
2390 startNode = startNode->traverseNextNode();
2394 // Insert a clone of the top blockquote after the break.
2395 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2396 clonedBlockquote->ref();
2397 clonedNodes.append(clonedBlockquote);
2398 insertNodeAfter(clonedBlockquote, m_breakNode);
2399 insertBlockPlaceholderIfNeeded(clonedBlockquote);
2401 // Make clones of ancestors in between the start node and the top blockquote.
2402 NodeImpl *parent = clonedBlockquote;
2403 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2404 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2406 clonedNodes.append(child);
2407 appendNode(child, parent);
2411 // Move the start node and the siblings of the start node.
2412 bool startIsBR = false;
2413 if (startNode != topBlockquote) {
2414 NodeImpl *n = startNode;
2415 bool startIsBR = n->id() == ID_BR;
2417 n = n->nextSibling();
2419 NodeImpl *next = n->nextSibling();
2421 appendNode(n, parent);
2426 // Move everything after the start node.
2427 NodeImpl *leftParent = ancestors.last();
2431 leftParent = topBlockquote;
2432 ElementImpl *b = document()->createHTMLElement("BR", exceptionCode);
2434 clonedNodes.append(b);
2435 ASSERT(exceptionCode == 0);
2436 appendNode(b, leftParent);
2439 leftParent = ancestors.last();
2440 while (leftParent && leftParent != topBlockquote) {
2441 parent = parent->parentNode();
2442 NodeImpl *n = leftParent->nextSibling();
2444 NodeImpl *next = n->nextSibling();
2446 appendNode(n, parent);
2449 leftParent = leftParent->parentNode();
2453 // Put the selection right before the break.
2454 setEndingSelection(Position(m_breakNode, 0));
2455 rebalanceWhitespace();
2458 //------------------------------------------------------------------------------------------
2459 // InsertTextCommand
2461 InsertTextCommand::InsertTextCommand(DocumentImpl *document)
2462 : CompositeEditCommand(document), m_charactersAdded(0)
2466 void InsertTextCommand::doApply()
2470 void InsertTextCommand::deleteCharacter()
2472 ASSERT(state() == Applied);
2474 Selection selection = endingSelection();
2476 if (!selection.start().node()->isTextNode())
2479 int exceptionCode = 0;
2480 int offset = selection.start().offset() - 1;
2481 if (offset >= selection.start().node()->caretMinOffset()) {
2482 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2483 textNode->deleteData(offset, 1, exceptionCode);
2484 ASSERT(exceptionCode == 0);
2485 selection = Selection(Position(textNode, offset));
2486 setEndingSelection(selection);
2487 m_charactersAdded--;
2491 Position InsertTextCommand::prepareForTextInsertion(bool adjustDownstream)
2493 // Prepare for text input by looking at the current position.
2494 // It may be necessary to insert a text node to receive characters.
2495 Selection selection = endingSelection();
2496 ASSERT(selection.isCaret());
2498 Position pos = selection.start();
2499 if (adjustDownstream)
2500 pos = pos.downstream(StayInBlock);
2502 pos = pos.upstream(StayInBlock);
2504 if (!pos.node()->isTextNode()) {
2505 NodeImpl *textNode = document()->createEditingTextNode("");
2506 NodeImpl *nodeToInsert = textNode;
2508 // Handle the case where there is a typing style.
2509 // FIXME: Improve typing style.
2510 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2511 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2512 if (typingStyle && typingStyle->length() > 0)
2513 nodeToInsert = applyTypingStyle(textNode);
2515 // Now insert the node in the right place
2516 if (pos.node()->isEditableBlock()) {
2517 LOG(Editing, "prepareForTextInsertion case 1");
2518 appendNode(nodeToInsert, pos.node());
2520 else if (pos.node()->caretMinOffset() == pos.offset()) {
2521 LOG(Editing, "prepareForTextInsertion case 2");
2522 insertNodeBefore(nodeToInsert, pos.node());
2524 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2525 LOG(Editing, "prepareForTextInsertion case 3");
2526 insertNodeAfter(nodeToInsert, pos.node());
2529 ASSERT_NOT_REACHED();
2531 pos = Position(textNode, 0);
2534 // Handle the case where there is a typing style.
2535 // FIXME: Improve typing style.
2536 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2537 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2538 if (typingStyle && typingStyle->length() > 0) {
2539 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2540 // Need to split current text node in order to insert a span.
2541 TextImpl *text = static_cast<TextImpl *>(pos.node());
2542 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2543 EditCommandPtr cmd(impl);
2544 applyCommandToComposite(cmd);
2545 setEndingSelection(Position(impl->node(), 0));
2548 TextImpl *editingTextNode = document()->createEditingTextNode("");
2549 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2550 if (node->isBlockFlow())
2551 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2553 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2554 pos = Position(editingTextNode, 0);
2560 void InsertTextCommand::input(const DOMString &text, bool selectInsertedText)
2562 Selection selection = endingSelection();
2563 bool adjustDownstream = isFirstVisiblePositionOnLine(VisiblePosition(selection.start().downstream(StayInBlock)));
2565 // Delete the current selection, or collapse whitespace, as needed
2566 if (selection.isRange())
2569 // Delete any insignificant text that could get in the way of whitespace turning
2570 // out correctly after the insertion.
2571 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2573 // Make sure the document is set up to receive text
2574 Position pos = prepareForTextInsertion(adjustDownstream);
2576 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2577 long offset = pos.offset();
2579 // Now that we are about to add content, check to see if a placeholder element
2581 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2583 // These are temporary implementations for inserting adjoining spaces
2584 // into a document. We are working on a CSS-related whitespace solution
2585 // that will replace this some day. We hope.
2587 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2588 // although the number of spaces varies (we choose four spaces).
2589 // Note that there is no attempt to make this work like a real tab stop, it is merely
2590 // a set number of spaces. This also seems to be the HTML editing convention.
2591 for (int i = 0; i < spacesPerTab; i++) {
2592 insertSpace(textNode, offset);
2593 rebalanceWhitespace();
2594 document()->updateLayout();
2596 if (selectInsertedText)
2597 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2599 setEndingSelection(Position(textNode, offset + spacesPerTab));
2600 m_charactersAdded += spacesPerTab;
2602 else if (isWS(text)) {
2603 insertSpace(textNode, offset);
2604 if (selectInsertedText)
2605 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2607 setEndingSelection(Position(textNode, offset + 1));
2608 m_charactersAdded++;
2609 rebalanceWhitespace();
2612 const DOMString &existingText = textNode->data();
2613 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2614 // DOM looks like this:
2615 // character nbsp caret
2616 // As we are about to insert a non-whitespace character at the caret
2617 // convert the nbsp to a regular space.
2618 // EDIT FIXME: This needs to be improved some day to convert back only
2619 // those nbsp's added by the editor to make rendering come out right.
2620 replaceTextInNode(textNode, offset - 1, 1, " ");
2622 insertTextIntoNode(textNode, offset, text);
2623 if (selectInsertedText)
2624 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2626 setEndingSelection(Position(textNode, offset + text.length()));
2627 m_charactersAdded += text.length();
2631 void InsertTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2635 DOMString text(textNode->data());
2637 // count up all spaces and newlines in front of the caret
2638 // delete all collapsed ones
2639 // this will work out OK since the offset we have been passed has been upstream-ized
2641 for (unsigned int i = offset; i < text.length(); i++) {
2648 // By checking the character at the downstream position, we can
2649 // check if there is a rendered WS at the caret
2650 Position pos(textNode, offset);
2651 Position downstream = pos.downstream();
2652 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2653 count--; // leave this WS in
2655 deleteTextFromNode(textNode, offset, count);
2658 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2659 // insert a "regular" space
2660 insertTextIntoNode(textNode, offset, " ");
2664 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2665 // DOM looks like this:
2667 // insert a space between the two nbsps
2668 insertTextIntoNode(textNode, offset - 1, " ");
2673 insertTextIntoNode(textNode, offset, nonBreakingSpaceString());
2676 bool InsertTextCommand::isInsertTextCommand() const
2681 //------------------------------------------------------------------------------------------
2682 // JoinTextNodesCommand
2684 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2685 : EditCommand(document), m_text1(text1), m_text2(text2)
2689 ASSERT(m_text1->nextSibling() == m_text2);
2690 ASSERT(m_text1->length() > 0);
2691 ASSERT(m_text2->length() > 0);
2697 JoinTextNodesCommand::~JoinTextNodesCommand()
2705 void JoinTextNodesCommand::doApply()
2709 ASSERT(m_text1->nextSibling() == m_text2);
2711 int exceptionCode = 0;
2712 m_text2->insertData(0, m_text1->data(), exceptionCode);
2713 ASSERT(exceptionCode == 0);
2715 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2716 ASSERT(exceptionCode == 0);
2718 m_offset = m_text1->length();
2721 void JoinTextNodesCommand::doUnapply()
2724 ASSERT(m_offset > 0);
2726 int exceptionCode = 0;
2728 m_text2->deleteData(0, m_offset, exceptionCode);
2729 ASSERT(exceptionCode == 0);
2731 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2732 ASSERT(exceptionCode == 0);
2734 ASSERT(m_text2->previousSibling()->isTextNode());
2735 ASSERT(m_text2->previousSibling() == m_text1);
2738 //------------------------------------------------------------------------------------------
2739 // MoveSelectionCommand
2741 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2742 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2748 MoveSelectionCommand::~MoveSelectionCommand()
2751 m_fragment->deref();
2754 void MoveSelectionCommand::doApply()
2756 Selection selection = endingSelection();
2757 ASSERT(selection.isRange());
2759 Position pos = m_position;
2761 // Update the position otherwise it may become invalid after the selection is deleted.
2762 NodeImpl *positionNode = m_position.node();
2763 long positionOffset = m_position.offset();
2764 Position selectionEnd = selection.end();
2765 long selectionEndOffset = selectionEnd.offset();
2766 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2767 positionOffset -= selectionEndOffset;
2768 Position selectionStart = selection.start();
2769 if (selectionStart.node() == positionNode) {
2770 positionOffset += selectionStart.offset();
2772 pos = Position(positionNode, positionOffset);
2775 deleteSelection(m_smartMove);
2777 // If the node for the destination has been removed as a result of the deletion,
2778 // set the destination to the ending point after the deletion.
2779 // Fixes: <rdar://problem/3910425> REGRESSION (Mail): Crash in ReplaceSelectionCommand;
2780 // selection is empty, leading to null deref
2781 if (!pos.node()->inDocument())
2782 pos = endingSelection().start();
2784 setEndingSelection(pos);
2785 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2786 applyCommandToComposite(cmd);
2789 //------------------------------------------------------------------------------------------
2790 // RebalanceWhitespaceCommand
2792 RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(DocumentImpl *document, const Position &pos)
2793 : EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset), m_downstreamOffset(InvalidOffset)
2797 RebalanceWhitespaceCommand::~RebalanceWhitespaceCommand()
2801 void RebalanceWhitespaceCommand::doApply()
2803 static DOMString space(" ");
2805 if (m_position.isNull() || !m_position.node()->isTextNode())
2808 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2809 DOMString text = textNode->data();
2810 if (text.length() == 0)
2813 // find upstream offset
2814 long upstream = m_position.offset();
2815 while (upstream > 0 && isWS(text[upstream - 1]) || isNBSP(text[upstream - 1])) {
2817 m_upstreamOffset = upstream;
2820 // find downstream offset
2821 long downstream = m_position.offset();
2822 while ((unsigned)downstream < text.length() && isWS(text[downstream]) || isNBSP(text[downstream])) {
2824 m_downstreamOffset = downstream;
2827 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2830 m_upstreamOffset = upstream;
2831 m_downstreamOffset = downstream;
2832 long length = m_downstreamOffset - m_upstreamOffset;
2834 m_beforeString = text.substring(m_upstreamOffset, length);
2836 // The following loop figures out a "rebalanced" whitespace string for any length
2837 // string, and takes into account the special cases that need to handled for the
2838 // start and end of strings (i.e. first and last character must be an nbsp.
2839 long i = m_upstreamOffset;
2840 while (i < m_downstreamOffset) {
2841 long add = (m_downstreamOffset - i) % 3;
2844 m_afterString += nonBreakingSpaceString();
2845 m_afterString += space;
2846 m_afterString += nonBreakingSpaceString();
2850 if (i == 0 || (unsigned)i + 1 == text.length()) // at start or end of string
2851 m_afterString += nonBreakingSpaceString();
2853 m_afterString += space;
2856 if ((unsigned)i + 2 == text.length()) {
2858 m_afterString += nonBreakingSpaceString();
2859 m_afterString += nonBreakingSpaceString();
2862 m_afterString += nonBreakingSpaceString();
2863 m_afterString += space;
2870 text.remove(m_upstreamOffset, length);
2871 text.insert(m_afterString, m_upstreamOffset);
2874 void RebalanceWhitespaceCommand::doUnapply()
2876 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2879 ASSERT(m_position.node()->isTextNode());
2880 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2881 DOMString text = textNode->data();
2882 text.remove(m_upstreamOffset, m_afterString.length());
2883 text.insert(m_beforeString, m_upstreamOffset);
2886 bool RebalanceWhitespaceCommand::preservesTypingStyle() const
2891 //------------------------------------------------------------------------------------------
2892 // RemoveCSSPropertyCommand
2894 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2895 : EditCommand(document), m_decl(decl->makeMutable()), m_property(property), m_important(false)
2901 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
2907 void RemoveCSSPropertyCommand::doApply()
2911 m_oldValue = m_decl->getPropertyValue(m_property);
2912 ASSERT(!m_oldValue.isNull());
2914 m_important = m_decl->getPropertyPriority(m_property);
2915 m_decl->removeProperty(m_property);
2918 void RemoveCSSPropertyCommand::doUnapply()
2921 ASSERT(!m_oldValue.isNull());
2923 m_decl->setProperty(m_property, m_oldValue, m_important);
2926 //------------------------------------------------------------------------------------------
2927 // RemoveNodeAttributeCommand
2929 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
2930 : EditCommand(document), m_element(element), m_attribute(attribute)
2936 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
2942 void RemoveNodeAttributeCommand::doApply()
2946 m_oldValue = m_element->getAttribute(m_attribute);
2947 ASSERT(!m_oldValue.isNull());
2949 int exceptionCode = 0;
2950 m_element->removeAttribute(m_attribute, exceptionCode);
2951 ASSERT(exceptionCode == 0);
2954 void RemoveNodeAttributeCommand::doUnapply()
2957 ASSERT(!m_oldValue.isNull());
2959 int exceptionCode = 0;
2960 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2961 ASSERT(exceptionCode == 0);
2964 //------------------------------------------------------------------------------------------
2965 // RemoveNodeCommand
2967 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
2968 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
2970 ASSERT(m_removeChild);
2971 m_removeChild->ref();
2973 m_parent = m_removeChild->parentNode();
2977 m_refChild = m_removeChild->nextSibling();
2982 RemoveNodeCommand::~RemoveNodeCommand()
2987 ASSERT(m_removeChild);
2988 m_removeChild->deref();
2991 m_refChild->deref();
2994 void RemoveNodeCommand::doApply()
2997 ASSERT(m_removeChild);
2999 int exceptionCode = 0;
3000 m_parent->removeChild(m_removeChild, exceptionCode);
3001 ASSERT(exceptionCode == 0);
3004 void RemoveNodeCommand::doUnapply()
3007 ASSERT(m_removeChild);
3009 int exceptionCode = 0;
3010 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
3011 ASSERT(exceptionCode == 0);
3014 //------------------------------------------------------------------------------------------
3015 // RemoveNodePreservingChildrenCommand
3017 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
3018 : CompositeEditCommand(document), m_node(node)
3024 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
3030 void RemoveNodePreservingChildrenCommand::doApply()
3032 while (NodeImpl* curr = node()->firstChild()) {
3034 insertNodeBefore(curr, node());
3039 //------------------------------------------------------------------------------------------
3040 // ReplaceSelectionCommand
3042 ReplacementFragment::ReplacementFragment(DocumentFragmentImpl *fragment)
3043 : m_fragment(fragment), m_hasInterchangeNewline(false), m_hasMoreThanOneBlock(false)
3046 m_type = EmptyFragment;
3052 NodeImpl *firstChild = m_fragment->firstChild();
3053 NodeImpl *lastChild = m_fragment->lastChild();
3056 m_type = EmptyFragment;
3060 if (firstChild == lastChild && firstChild->isTextNode()) {
3061 m_type = SingleTextNodeFragment;
3065 m_type = TreeFragment;
3067 NodeImpl *node = firstChild;
3068 int realBlockCount = 0;
3069 NodeImpl *nodeToDelete = 0;
3071 NodeImpl *next = node->traverseNextNode();
3072 if (isInterchangeNewlineNode(node)) {
3073 m_hasInterchangeNewline = true;
3074 nodeToDelete = node;
3076 else if (isInterchangeConvertedSpaceSpan(node)) {
3078 while ((n = node->firstChild())) {
3081 insertNodeBefore(n, node);
3086 next = n->traverseNextNode();
3088 else if (isProbablyBlock(node))
3094 removeNode(nodeToDelete);
3096 int blockCount = realBlockCount;
3097 firstChild = m_fragment->firstChild();
3098 lastChild = m_fragment->lastChild();
3099 if (!isProbablyBlock(firstChild))
3101 if (!isProbablyBlock(lastChild) && realBlockCount > 0)
3105 m_hasMoreThanOneBlock = true;
3108 ReplacementFragment::~ReplacementFragment()
3111 m_fragment->deref();
3114 NodeImpl *ReplacementFragment::firstChild() const
3116 return m_fragment->firstChild();
3119 NodeImpl *ReplacementFragment::lastChild() const
3121 return m_fragment->lastChild();
3124 NodeImpl *ReplacementFragment::mergeStartNode() const
3126 NodeImpl *node = m_fragment->firstChild();
3128 NodeImpl *next = node->traverseNextNode();
3129 if (!isProbablyBlock(node))
3136 NodeImpl *ReplacementFragment::mergeEndNode() const
3138 NodeImpl *node = m_fragment->lastChild();
3139 while (node && node->lastChild())
3140 node = node->lastChild();
3142 if (isProbablyBlock(node))
3145 NodeImpl *startingBlock = enclosingBlock(node);
3146 ASSERT(startingBlock != node);
3148 NodeImpl *prev = node->traversePreviousNode();
3149 if (prev == m_fragment || prev == startingBlock || enclosingBlock(prev) != startingBlock)
3157 void ReplacementFragment::pruneEmptyNodes()
3162 NodeImpl *node = m_fragment->firstChild();
3164 if ((node->isTextNode() && static_cast<TextImpl *>(node)->length() == 0) ||
3165 (isProbablyBlock(node) && node->childNodeCount() == 0)) {
3166 NodeImpl *next = node->traverseNextSibling();
3172 node = node->traverseNextNode();
3178 bool ReplacementFragment::isInterchangeNewlineNode(const NodeImpl *node)
3180 static DOMString interchangeNewlineClassString(AppleInterchangeNewline);
3181 return node && node->id() == ID_BR && static_cast<const ElementImpl *>(node)->getAttribute(ATTR_CLASS) == interchangeNewlineClassString;
3184 bool ReplacementFragment::isInterchangeConvertedSpaceSpan(const NodeImpl *node)
3186 static DOMString convertedSpaceSpanClassString(AppleConvertedSpace);
3187 return node->isHTMLElement() && static_cast<const HTMLElementImpl *>(node)->getAttribute(ATTR_CLASS) == convertedSpaceSpanClassString;
3190 NodeImpl *ReplacementFragment::enclosingBlock(NodeImpl *node) const
3192 while (node && !isProbablyBlock(node))
3193 node = node->parentNode();
3194 return node ? node : m_fragment;
3197 void ReplacementFragment::removeNode(NodeImpl *node)
3202 NodeImpl *parent = node->parentNode();
3206 int exceptionCode = 0;
3207 parent->removeChild(node, exceptionCode);
3208 ASSERT(exceptionCode == 0);
3211 void ReplacementFragment::insertNodeBefore(NodeImpl *node, NodeImpl *refNode)
3213 if (!node || !refNode)
3216 NodeImpl *parent = refNode->parentNode();
3220 int exceptionCode = 0;
3221 parent->insertBefore(node, refNode, exceptionCode);
3222 ASSERT(exceptionCode == 0);
3226 bool isProbablyBlock(const NodeImpl *node)
3231 switch (node->id()) {
3257 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
3258 : CompositeEditCommand(document),
3259 m_fragment(fragment),
3260 m_selectReplacement(selectReplacement),
3261 m_smartReplace(smartReplace)
3265 ReplaceSelectionCommand::~ReplaceSelectionCommand()
3269 void ReplaceSelectionCommand::doApply()
3271 Selection selection = endingSelection();
3272 VisiblePosition visibleStart(selection.start());
3273 VisiblePosition visibleEnd(selection.end());
3274 bool startAtStartOfLine = isFirstVisiblePositionOnLine(visibleStart);
3275 bool startAtStartOfBlock = isFirstVisiblePositionInBlock(visibleStart);
3276 bool startAtEndOfBlock = isLastVisiblePositionInBlock(visibleStart);
3277 bool startAtBlockBoundary = startAtStartOfBlock || startAtEndOfBlock;
3278 NodeImpl *startBlock = selection.start().node()->enclosingBlockFlowElement();
3279 NodeImpl *endBlock = selection.end().node()->enclosingBlockFlowElement();
3281 bool mergeStart = !(startAtStartOfLine && (m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()));
3282 bool mergeEnd = !m_fragment.hasInterchangeNewline() && m_fragment.hasMoreThanOneBlock();
3283 Position startPos = Position(selection.start().node()->enclosingBlockFlowElement(), 0);
3285 EStayInBlock upstreamStayInBlock = StayInBlock;
3287 // Delete the current selection, or collapse whitespace, as needed
3288 if (selection.isRange()) {
3289 deleteSelection(false, !(m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()));
3291 else if (selection.isCaret() && mergeEnd && !startAtBlockBoundary) {
3292 // The start and the end need to wind up in separate blocks.
3293 // Insert a paragraph separator to make that happen.
3294 insertParagraphSeparator();
3295 upstreamStayInBlock = DoNotStayInBlock;
3298 selection = endingSelection();
3299 if (startAtStartOfBlock && startBlock->inDocument())
3300 startPos = Position(startBlock, 0);
3301 else if (startAtEndOfBlock)
3302 startPos = selection.start().downstream(StayInBlock);
3304 startPos = selection.start().upstream(upstreamStayInBlock);
3305 endPos = selection.end().downstream();
3307 // This command does not use any typing style that is set as a residual effect of
3309 // FIXME: Improve typing style.
3310 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3311 KHTMLPart *part = document()->part();
3312 part->clearTypingStyle();
3315 if (!m_fragment.firstChild())
3318 // Now that we are about to add content, check to see if a placeholder element
3320 NodeImpl *block = startPos.node()->enclosingBlockFlowElement();
3321 if (removeBlockPlaceholderIfNeeded(block)) {
3322 Position pos = Position(block, 0);
3323 if (!endPos.node()->inDocument()) // endPos might have been in the placeholder just removed.
3328 bool addLeadingSpace = false;
3329 bool addTrailingSpace = false;
3330 if (m_smartReplace) {
3331 addLeadingSpace = startPos.leadingWhitespacePosition().isNotNull();
3332 if (addLeadingSpace) {
3333 QChar previousChar = VisiblePosition(startPos).previous().character();
3334 if (!previousChar.isNull()) {
3335 addLeadingSpace = !part->isCharacterSmartReplaceExempt(previousChar, true);
3338 addTrailingSpace = endPos.trailingWhitespacePosition().isNotNull();
3339 if (addTrailingSpace) {
3340 QChar thisChar = VisiblePosition(endPos).character();
3341 if (!thisChar.isNull()) {
3342 addTrailingSpace = !part->isCharacterSmartReplaceExempt(thisChar, false);
3347 document()->updateLayout();
3349 NodeImpl *refBlock = startPos.node()->enclosingBlockFlowElement();
3350 Position insertionPos = startPos;
3351 bool insertBlocksBefore = true;
3353 NodeImpl *firstNodeInserted = 0;
3354 NodeImpl *lastNodeInserted = 0;
3355 bool lastNodeInsertedInMergeEnd = false;
3357 // prune empty nodes from fragment
3358 m_fragment.pruneEmptyNodes();
3360 // Merge content into the end block, if necessary.
3362 NodeImpl *node = m_fragment.mergeEndNode();
3364 NodeImpl *refNode = node;
3365 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3366 insertNodeAt(refNode, endPos.node(), endPos.offset());
3367 firstNodeInserted = refNode;
3368 lastNodeInserted = refNode;
3369 while (node && !isProbablyBlock(node)) {
3370 NodeImpl *next = node->nextSibling();
3371 insertNodeAfter(node, refNode);
3372 lastNodeInserted = node;
3376 lastNodeInsertedInMergeEnd = true;
3380 // prune empty nodes from fragment
3381 m_fragment.pruneEmptyNodes();
3383 // Merge content into the start block, if necessary.
3385 NodeImpl *node = m_fragment.mergeStartNode();
3386 NodeImpl *insertionNode = 0;
3388 NodeImpl *refNode = node;
3389 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3390 insertNodeAt(refNode, startPos.node(), startPos.offset());
3391 firstNodeInserted = refNode;
3392 if (!lastNodeInsertedInMergeEnd)
3393 lastNodeInserted = refNode;
3394 insertionNode = refNode;
3395 while (node && !isProbablyBlock(node)) {
3396 NodeImpl *next = node->nextSibling();
3397 insertNodeAfter(node, refNode);
3398 if (!lastNodeInsertedInMergeEnd)
3399 lastNodeInserted = node;
3400 insertionNode = node;
3406 insertionPos = Position(insertionNode, insertionNode->caretMaxOffset());
3407 insertBlocksBefore = false;
3410 // prune empty nodes from fragment
3411 m_fragment.pruneEmptyNodes();
3413 // Merge everything remaining.
3414 NodeImpl *node = m_fragment.firstChild();
3416 NodeImpl *refNode = node;
3417 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3418 if (isProbablyBlock(refNode) && (insertBlocksBefore || startAtStartOfBlock) && !mergeStart) {
3419 if (refBlock->id() == ID_BODY)
3420 insertNodeAt(refNode, refBlock, 0);
3422 insertNodeBefore(refNode, refBlock);
3424 else if (isProbablyBlock(refNode) && startAtEndOfBlock && !mergeEnd) {
3425 if (refBlock->id() == ID_BODY)
3426 appendNode(refNode, refBlock);
3428 insertNodeAfter(refNode, refBlock);
3431 insertNodeAt(refNode, insertionPos.node(), insertionPos.offset());
3433 if (!firstNodeInserted)
3434 firstNodeInserted = refNode;
3435 if (!lastNodeInsertedInMergeEnd)
3436 lastNodeInserted = refNode;
3438 NodeImpl *next = node->nextSibling();
3439 insertNodeAfter(node, refNode);
3440 if (!lastNodeInsertedInMergeEnd)
3441 lastNodeInserted = node;
3445 document()->updateLayout();
3446 insertionPos = Position(lastNodeInserted, lastNodeInserted->caretMaxOffset());
3449 // Handle "smart replace" whitespace
3450 if (addTrailingSpace && lastNodeInserted) {
3451 if (lastNodeInserted->isTextNode()) {
3452 TextImpl *text = static_cast<TextImpl *>(lastNodeInserted);
3453 insertTextIntoNode(text, text->length(), nonBreakingSpaceString());
3454 insertionPos = Position(text, text->length());
3457 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3458 insertNodeAfter(node, lastNodeInserted);
3459 if (!firstNodeInserted)
3460 firstNodeInserted = node;
3461 lastNodeInserted = node;
3462 insertionPos = Position(node, 1);
3466 if (addLeadingSpace && firstNodeInserted) {
3467 if (firstNodeInserted->isTextNode()) {
3468 TextImpl *text = static_cast<TextImpl *>(firstNodeInserted);
3469 insertTextIntoNode(text, 0, nonBreakingSpaceString());
3472 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3473 insertNodeBefore(node, firstNodeInserted);
3474 firstNodeInserted = node;
3475 if (!lastNodeInsertedInMergeEnd)
3476 lastNodeInserted = node;
3480 // Handle trailing newline
3481 if (m_fragment.hasInterchangeNewline()) {
3482 if (startBlock == endBlock && !isProbablyBlock(lastNodeInserted)) {
3483 setEndingSelection(insertionPos);
3484 insertParagraphSeparator();
3485 endPos = endingSelection().end().downstream();
3487 completeHTMLReplacement(startPos, endPos);
3490 if (lastNodeInserted->id() == ID_BR && !document()->inStrictMode()) {
3491 document()->updateLayout();
3492 VisiblePosition pos(Position(lastNodeInserted, 0));
3493 if (isLastVisiblePositionInBlock(pos)) {
3494 NodeImpl *next = lastNodeInserted->traverseNextNode();
3495 bool hasTrailingBR = next && next->id() == ID_BR && lastNodeInserted->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
3496 if (!hasTrailingBR) {
3497 // Insert an "extra" BR at the end of the block.
3498 int exceptionCode = 0;
3499 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
3500 ASSERT(exceptionCode == 0);
3501 insertNodeBefore(extraBreakNode, lastNodeInserted);
3505 completeHTMLReplacement(firstNodeInserted, lastNodeInserted);
3509 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &start, const Position &end)
3511 if (start.isNull() || !start.node()->inDocument() || end.isNull() || !end.node()->inDocument())
3513 m_selectReplacement ? setEndingSelection(Selection(start, end)) : setEndingSelection(end);
3514 rebalanceWhitespace();
3517 void ReplaceSelectionCommand::completeHTMLReplacement(NodeImpl *firstNodeInserted, NodeImpl *lastNodeInserted)
3519 if (!firstNodeInserted || !firstNodeInserted->inDocument() ||
3520 !lastNodeInserted || !lastNodeInserted->inDocument())
3523 // Find the last leaf.
3524 NodeImpl *lastLeaf = lastNodeInserted;
3526 NodeImpl *nextChild = lastLeaf->lastChild();
3529 lastLeaf = nextChild;
3532 // Find the first leaf.
3533 NodeImpl *firstLeaf = firstNodeInserted;
3535 NodeImpl *nextChild = firstLeaf->firstChild();
3538 firstLeaf = nextChild;
3541 Position start(firstLeaf, firstLeaf->caretMinOffset());
3542 Position end(lastLeaf, lastLeaf->caretMaxOffset());
3543 Selection replacementSelection(start, end);
3544 if (m_selectReplacement) {
3545 // Select what was inserted.
3546 setEndingSelection(replacementSelection);
3549 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
3550 setEndingSelection(end);
3552 rebalanceWhitespace();
3555 //------------------------------------------------------------------------------------------
3556 // SetNodeAttributeCommand
3558 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
3559 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
3563 ASSERT(!m_value.isNull());
3566 SetNodeAttributeCommand::~SetNodeAttributeCommand()
3572 void SetNodeAttributeCommand::doApply()
3575 ASSERT(!m_value.isNull());
3577 int exceptionCode = 0;
3578 m_oldValue = m_element->getAttribute(m_attribute);
3579 m_element->setAttribute(m_attribute, m_value.implementation(), exceptionCode);
3580 ASSERT(exceptionCode == 0);
3583 void SetNodeAttributeCommand::doUnapply()
3586 ASSERT(!m_oldValue.isNull());
3588 int exceptionCode = 0;
3589 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
3590 ASSERT(exceptionCode == 0);
3593 //------------------------------------------------------------------------------------------
3594 // SplitTextNodeCommand
3596 SplitTextNodeCommand::SplitTextNodeCommand(DocumentImpl *document, TextImpl *text, long offset)
3597 : EditCommand(document), m_text1(0), m_text2(text), m_offset(offset)
3600 ASSERT(m_text2->length() > 0);
3605 SplitTextNodeCommand::~SplitTextNodeCommand()
3614 void SplitTextNodeCommand::doApply()
3617 ASSERT(m_offset > 0);
3619 int exceptionCode = 0;
3621 // EDIT FIXME: This should use better smarts for figuring out which portion
3622 // of the split to copy (based on their comparitive sizes). We should also
3623 // just use the DOM's splitText function.
3626 // create only if needed.
3627 // if reapplying, this object will already exist.
3628 m_text1 = document()->createTextNode(m_text2->substringData(0, m_offset, exceptionCode));
3629 ASSERT(exceptionCode == 0);
3634 m_text2->deleteData(0, m_offset, exceptionCode);
3635 ASSERT(exceptionCode == 0);
3637 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
3638 ASSERT(exceptionCode == 0);
3640 ASSERT(m_text2->previousSibling()->isTextNode());
3641 ASSERT(m_text2->previousSibling() == m_text1);
3644 void SplitTextNodeCommand::doUnapply()
3649 ASSERT(m_text1->nextSibling() == m_text2);
3651 int exceptionCode = 0;
3652 m_text2->insertData(0, m_text1->data(), exceptionCode);
3653 ASSERT(exceptionCode == 0);
3655 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
3656 ASSERT(exceptionCode == 0);
3658 m_offset = m_text1->length();
3661 //------------------------------------------------------------------------------------------
3664 TypingCommand::TypingCommand(DocumentImpl *document, ETypingCommand commandType, const DOMString &textToInsert, bool selectInsertedText)
3665 : CompositeEditCommand(document), m_commandType(commandType), m_textToInsert(textToInsert), m_openForMoreTyping(true), m_applyEditing(false), m_selectInsertedText(selectInsertedText)
3669 void TypingCommand::deleteKeyPressed(DocumentImpl *document)
3673 KHTMLPart *part = document->part();
3676 EditCommandPtr lastEditCommand = part->lastEditCommand();
3677 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3678 static_cast<TypingCommand *>(lastEditCommand.get())->deleteKeyPressed();
3681 EditCommandPtr cmd(new TypingCommand(document, DeleteKey));
3686 void TypingCommand::insertText(DocumentImpl *document, const DOMString &text, bool selectInsertedText)
3690 KHTMLPart *part = document->part();
3693 EditCommandPtr lastEditCommand = part->lastEditCommand();
3694 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3695 static_cast<TypingCommand *>(lastEditCommand.get())->insertText(text, selectInsertedText);
3698 EditCommandPtr cmd(new TypingCommand(document, InsertText, text, selectInsertedText));
3703 void TypingCommand::insertLineBreak(DocumentImpl *document)
3707 KHTMLPart *part = document->part();
3710 EditCommandPtr lastEditCommand = part->lastEditCommand();
3711 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3712 static_cast<TypingCommand *>(lastEditCommand.get())->insertLineBreak();
3715 EditCommandPtr cmd(new TypingCommand(document, InsertLineBreak));
3720 void TypingCommand::insertParagraphSeparatorInQuotedContent(DocumentImpl *document)
3724 KHTMLPart *part = document->part();
3727 EditCommandPtr lastEditCommand = part->lastEditCommand();
3728 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3729 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparatorInQuotedContent();
3732 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparatorInQuotedContent));
3737 void TypingCommand::insertParagraphSeparator(DocumentImpl *document)
3741 KHTMLPart *part = document->part();
3744 EditCommandPtr lastEditCommand = part->lastEditCommand();
3745 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3746 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparator();
3749 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparator));
3754 bool TypingCommand::isOpenForMoreTypingCommand(const EditCommandPtr &cmd)
3756 return cmd.isTypingCommand() &&
3757 static_cast<const TypingCommand *>(cmd.get())->openForMoreTyping();
3760 void TypingCommand::closeTyping(const EditCommandPtr &cmd)
3762 if (isOpenForMoreTypingCommand(cmd))
3763 static_cast<TypingCommand *>(cmd.get())->closeTyping();
3766 void TypingCommand::doApply()
3768 if (endingSelection().isNone())
3771 switch (m_commandType) {
3775 case InsertLineBreak:
3778 case InsertParagraphSeparator:
3779 insertParagraphSeparator();
3781 case InsertParagraphSeparatorInQuotedContent:
3782 insertParagraphSeparatorInQuotedContent();
3785 insertText(m_textToInsert, m_selectInsertedText);
3789 ASSERT_NOT_REACHED();
3792 HTMLEditAction TypingCommand::editingAction() const
3794 return HTMLEditActionTyping;
3797 void TypingCommand::markMisspellingsAfterTyping()
3799 // Take a look at the selection that results after typing and determine whether we need to spellcheck.
3800 // Since the word containing the current selection is never marked, this does a check to
3801 // see if typing made a new word that is not in the current selection. Basically, you
3802 // get this by being at the end of a word and typing a space.
3803 VisiblePosition start(endingSelection().start());
3804 VisiblePosition previous = start.previous();
3805 if (previous.isNotNull()) {
3806 VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
3807 VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
3809 KWQ(document()->part())->markMisspellingsInAdjacentWords(p1);
3813 void TypingCommand::typingAddedToOpenCommand()
3815 markMisspellingsAfterTyping();
3816 // Do not apply editing to the part on the first time through.
3817 // The part will get told in the same way as all other commands.
3818 // But since this command stays open and is used for additional typing,
3819 // we need to tell the part here as other commands are added.
3820 if (m_applyEditing) {
3821 EditCommandPtr cmd(this);
3822 document()->part()->appliedEditing(cmd);
3824 m_applyEditing = true;
3827 void TypingCommand::insertText(const DOMString &text, bool selectInsertedText)
3829 // FIXME: Improve typing style.
3830 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3831 if (document()->part()->typingStyle() || m_cmds.count() == 0) {
3832 InsertTextCommand *impl = new InsertTextCommand(document());
3833 EditCommandPtr cmd(impl);
3834 applyCommandToComposite(cmd);
3835 impl->input(text, selectInsertedText);
3838 EditCommandPtr lastCommand = m_cmds.last();
3839 if (lastCommand.isInsertTextCommand()) {
3840 InsertTextCommand *impl = static_cast<InsertTextCommand *>(lastCommand.get());
3841 impl->input(text, selectInsertedText);
3844 InsertTextCommand *impl = new InsertTextCommand(document());
3845 EditCommandPtr cmd(impl);
3846 applyCommandToComposite(cmd);
3847 impl->input(text, selectInsertedText);
3850 typingAddedToOpenCommand();
3853 void TypingCommand::insertLineBreak()
3855 EditCommandPtr cmd(new InsertLineBreakCommand(document()));
3856 applyCommandToComposite(cmd);
3857 typingAddedToOpenCommand();
3860 void TypingCommand::insertParagraphSeparator()
3862 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
3863 applyCommandToComposite(cmd);
3864 typingAddedToOpenCommand();
3867 void TypingCommand::insertParagraphSeparatorInQuotedContent()
3869 EditCommandPtr cmd(new InsertParagraphSeparatorInQuotedContentCommand(document()));
3870 applyCommandToComposite(cmd);
3871 typingAddedToOpenCommand();
3874 void TypingCommand::issueCommandForDeleteKey()
3876 Selection selectionToDelete;
3878 switch (endingSelection().state()) {
3879 case Selection::RANGE:
3880 selectionToDelete = endingSelection();
3882 case Selection::CARET: {
3883 // Handle delete at beginning-of-block case.
3884 // Do nothing in the case that the caret is at the start of a
3885 // root editable element or at the start of a document.
3886 Position pos(endingSelection().start());
3887 Position start = VisiblePosition(pos).previous().deepEquivalent();
3888 Position end = VisiblePosition(pos).deepEquivalent();
3889 if (start.isNotNull() && end.isNotNull() && start.node()->rootEditableElement() == end.node()->rootEditableElement())
3890 selectionToDelete = Selection(start, end);
3893 case Selection::NONE:
3894 ASSERT_NOT_REACHED();
3898 if (selectionToDelete.isCaretOrRange()) {
3899 deleteSelection(selectionToDelete);
3900 typingAddedToOpenCommand();
3904 void TypingCommand::deleteKeyPressed()
3906 // EDIT FIXME: The ifdef'ed out code below should be re-enabled.
3907 // In order for this to happen, the deleteCharacter case
3908 // needs work. Specifically, the caret-positioning code
3909 // and whitespace-handling code in DeleteSelectionCommand::doApply()
3910 // needs to be factored out so it can be used again here.
3911 // Until that work is done, issueCommandForDeleteKey() does the
3912 // right thing, but less efficiently and with the cost of more
3914 issueCommandForDeleteKey();
3916 if (m_cmds.count() == 0) {
3917 issueCommandForDeleteKey();
3920 EditCommandPtr lastCommand = m_cmds.last();
3921 if (lastCommand.isInsertTextCommand()) {
3922 InsertTextCommand &cmd = static_cast<InsertTextCommand &>(lastCommand);
3923 cmd.deleteCharacter();
3924 if (cmd.charactersAdded() == 0) {
3925 removeCommand(lastCommand);
3928 else if (lastCommand.isInsertLineBreakCommand()) {
3929 lastCommand.unapply();
3930 removeCommand(lastCommand);
3933 issueCommandForDeleteKey();
3939 void TypingCommand::removeCommand(const EditCommandPtr &cmd)
3941 // NOTE: If the passed-in command is the last command in the
3942 // composite, we could remove all traces of this typing command
3943 // from the system, including the undo chain. Other editors do
3944 // not do this, but we could.
3947 if (m_cmds.count() == 0)
3948 setEndingSelection(startingSelection());
3950 setEndingSelection(m_cmds.last().endingSelection());
3953 bool TypingCommand::preservesTypingStyle() const
3955 switch (m_commandType) {
3958 case InsertLineBreak:
3959 case InsertParagraphSeparator:
3960 case InsertParagraphSeparatorInQuotedContent:
3964 ASSERT_NOT_REACHED();
3968 bool TypingCommand::isTypingCommand() const
3973 } // namespace khtml