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 DocumentImpl * const EditCommandPtr::document() const
271 IF_IMPL_NULL_RETURN_ARG(0);
272 return get()->document();
275 Selection EditCommandPtr::startingSelection() const
277 IF_IMPL_NULL_RETURN_ARG(Selection());
278 return get()->startingSelection();
281 Selection EditCommandPtr::endingSelection() const
283 IF_IMPL_NULL_RETURN_ARG(Selection());
284 return get()->endingSelection();
287 void EditCommandPtr::setStartingSelection(const Selection &s) const
290 get()->setStartingSelection(s);
293 void EditCommandPtr::setEndingSelection(const Selection &s) const
296 get()->setEndingSelection(s);
299 CSSMutableStyleDeclarationImpl *EditCommandPtr::typingStyle() const
301 IF_IMPL_NULL_RETURN_ARG(0);
302 return get()->typingStyle();
305 void EditCommandPtr::setTypingStyle(CSSMutableStyleDeclarationImpl *style) const
308 get()->setTypingStyle(style);
311 EditCommandPtr EditCommandPtr::parent() const
313 IF_IMPL_NULL_RETURN_ARG(0);
314 return get()->parent();
317 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
320 get()->setParent(cmd.get());
323 EditCommandPtr &EditCommandPtr::emptyCommand()
325 static EditCommandPtr m_emptyCommand;
326 return m_emptyCommand;
329 //------------------------------------------------------------------------------------------
332 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, ELegacyHTMLStyles usesLegacyStyles)
333 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
335 init(style, Position());
338 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
339 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
341 init(style, position);
344 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
347 CSSMutableStyleDeclarationImpl *mutableStyle = style->makeMutable();
351 QString styleText("");
353 QValueListConstIterator<CSSProperty> end;
354 for (QValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
355 const CSSProperty *property = &*it;
357 // If position is empty or the position passed in already has the
358 // style, just move on.
359 if (position.isNotNull() && currentlyHasStyle(position, property))
362 // If needed, figure out if this change is a legacy HTML style change.
363 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
367 styleText += property->cssText().string();
370 mutableStyle->deref();
372 // Save the result for later
373 m_cssStyle = styleText.stripWhiteSpace();
376 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
378 DOMString valueText(property->value()->cssText());
379 switch (property->id()) {
380 case CSS_PROP_FONT_WEIGHT:
381 if (strcasecmp(valueText, "bold") == 0) {
386 case CSS_PROP_FONT_STYLE:
387 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
388 m_applyItalic = true;
396 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
398 ASSERT(pos.isNotNull());
399 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
402 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
407 bool result = strcasecmp(value->cssText(), property->value()->cssText()) == 0;
412 //------------------------------------------------------------------------------------------
415 EditCommand::EditCommand(DocumentImpl *document)
416 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
419 ASSERT(m_document->part());
421 m_startingSelection = m_document->part()->selection();
422 m_endingSelection = m_startingSelection;
424 m_document->part()->setSelection(Selection(), false, true);
427 EditCommand::~EditCommand()
432 m_typingStyle->deref();
435 void EditCommand::apply()
438 ASSERT(m_document->part());
439 ASSERT(state() == NotApplied);
441 KHTMLPart *part = m_document->part();
443 ASSERT(part->selection().isNone());
449 // FIXME: Improve typing style.
450 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
451 if (!preservesTypingStyle())
454 if (!isCompositeStep()) {
455 document()->updateLayout();
456 EditCommandPtr cmd(this);
457 part->appliedEditing(cmd);
461 void EditCommand::unapply()
464 ASSERT(m_document->part());
465 ASSERT(state() == Applied);
467 bool topLevel = !isCompositeStep();
469 KHTMLPart *part = m_document->part();
472 part->setSelection(Selection(), false, true);
474 ASSERT(part->selection().isNone());
478 m_state = NotApplied;
481 document()->updateLayout();
482 EditCommandPtr cmd(this);
483 part->unappliedEditing(cmd);
487 void EditCommand::reapply()
490 ASSERT(m_document->part());
491 ASSERT(state() == NotApplied);
493 bool topLevel = !isCompositeStep();
495 KHTMLPart *part = m_document->part();
498 part->setSelection(Selection(), false, true);
500 ASSERT(part->selection().isNone());
507 document()->updateLayout();
508 EditCommandPtr cmd(this);
509 part->reappliedEditing(cmd);
513 void EditCommand::doReapply()
518 void EditCommand::setStartingSelection(const Selection &s)
520 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
521 cmd->m_startingSelection = s;
524 void EditCommand::setEndingSelection(const Selection &s)
526 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
527 cmd->m_endingSelection = s;
530 void EditCommand::assignTypingStyle(CSSMutableStyleDeclarationImpl *style)
532 if (m_typingStyle == style)
535 CSSMutableStyleDeclarationImpl *old = m_typingStyle;
536 m_typingStyle = style;
538 m_typingStyle->ref();
543 void EditCommand::setTypingStyle(CSSMutableStyleDeclarationImpl *style)
545 // FIXME: Improve typing style.
546 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
547 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
548 cmd->assignTypingStyle(style);
551 bool EditCommand::preservesTypingStyle() const
556 bool EditCommand::isInsertTextCommand() const
561 bool EditCommand::isTypingCommand() const
566 //------------------------------------------------------------------------------------------
567 // CompositeEditCommand
569 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
570 : EditCommand(document)
574 void CompositeEditCommand::doUnapply()
576 if (m_cmds.count() == 0) {
580 for (int i = m_cmds.count() - 1; i >= 0; --i)
581 m_cmds[i]->unapply();
583 setState(NotApplied);
586 void CompositeEditCommand::doReapply()
588 if (m_cmds.count() == 0) {
592 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
599 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
601 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
603 cmd.setStartingSelection(endingSelection());
604 cmd.setEndingSelection(endingSelection());
610 void CompositeEditCommand::insertParagraphSeparator()
612 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
613 applyCommandToComposite(cmd);
616 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
618 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
619 applyCommandToComposite(cmd);
622 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
624 if (refChild->parentNode()->lastChild() == refChild) {
625 appendNode(insertChild, refChild->parentNode());
628 ASSERT(refChild->nextSibling());
629 insertNodeBefore(insertChild, refChild->nextSibling());
633 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
635 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
636 NodeImpl *child = refChild->firstChild();
637 for (long i = 0; child && i < offset; i++)
638 child = child->nextSibling();
640 insertNodeBefore(insertChild, child);
642 appendNode(insertChild, refChild);
644 else if (refChild->caretMinOffset() >= offset) {
645 insertNodeBefore(insertChild, refChild);
647 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
648 splitTextNode(static_cast<TextImpl *>(refChild), offset);
649 insertNodeBefore(insertChild, refChild);
652 insertNodeAfter(insertChild, refChild);
656 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
658 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
659 applyCommandToComposite(cmd);
662 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
664 if (isTableStructureNode(node)) {
665 // Do not remove an element of table structure; remove its contents.
666 NodeImpl *child = node->firstChild();
668 NodeImpl *remove = child;
669 child = child->nextSibling();
670 removeFullySelectedNode(remove);
674 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
675 applyCommandToComposite(cmd);
679 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
681 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
682 applyCommandToComposite(cmd);
685 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
687 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
688 applyCommandToComposite(cmd);
691 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
693 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
694 applyCommandToComposite(cmd);
697 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
699 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
700 applyCommandToComposite(cmd);
703 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
705 InsertTextCommand *impl = new InsertTextCommand(document());
706 EditCommandPtr cmd(impl);
707 applyCommandToComposite(cmd);
708 impl->input(text, selectInsertedText);
711 void CompositeEditCommand::insertTextIntoNode(TextImpl *node, long offset, const DOMString &text)
713 EditCommandPtr cmd(new InsertIntoTextNode(document(), node, offset, text));
714 applyCommandToComposite(cmd);
717 void CompositeEditCommand::deleteTextFromNode(TextImpl *node, long offset, long count)
719 EditCommandPtr cmd(new DeleteFromTextNodeCommand(document(), node, offset, count));
720 applyCommandToComposite(cmd);
723 void CompositeEditCommand::replaceTextInNode(TextImpl *node, long offset, long count, const DOMString &replacementText)
725 EditCommandPtr deleteCommand(new DeleteFromTextNodeCommand(document(), node, offset, count));
726 applyCommandToComposite(deleteCommand);
727 EditCommandPtr insertCommand(new InsertIntoTextNode(document(), node, offset, replacementText));
728 applyCommandToComposite(insertCommand);
731 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
733 if (endingSelection().isRange()) {
734 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
735 applyCommandToComposite(cmd);
739 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
741 if (selection.isRange()) {
742 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
743 applyCommandToComposite(cmd);
747 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
749 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
750 applyCommandToComposite(cmd);
753 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
755 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
756 applyCommandToComposite(cmd);
759 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
761 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
762 applyCommandToComposite(cmd);
765 void CompositeEditCommand::rebalanceWhitespace()
767 Selection selection = endingSelection();
768 if (selection.isCaretOrRange()) {
769 EditCommandPtr startCmd(new RebalanceWhitespaceCommand(document(), endingSelection().start()));
770 applyCommandToComposite(startCmd);
771 if (selection.isRange()) {
772 EditCommandPtr endCmd(new RebalanceWhitespaceCommand(document(), endingSelection().end()));
773 applyCommandToComposite(endCmd);
778 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
780 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
781 // and ApplyStyleCommand::computeStyleChange.
782 // Both function do similar work, and the common parts could be factored out.
784 // FIXME: Improve typing style.
785 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
787 // update document layout once before running the rest of the function
788 // so that we avoid the expense of updating before each and every call
789 // to check a computed style
790 document()->updateLayout();
792 StyleChange styleChange(document()->part()->typingStyle());
794 NodeImpl *childToAppend = child;
795 int exceptionCode = 0;
797 if (styleChange.applyItalic()) {
798 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
799 ASSERT(exceptionCode == 0);
800 italicElement->appendChild(childToAppend, exceptionCode);
801 ASSERT(exceptionCode == 0);
802 childToAppend = italicElement;
805 if (styleChange.applyBold()) {
806 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
807 ASSERT(exceptionCode == 0);
808 boldElement->appendChild(childToAppend, exceptionCode);
809 ASSERT(exceptionCode == 0);
810 childToAppend = boldElement;
813 if (styleChange.cssStyle().length() > 0) {
814 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
815 ASSERT(exceptionCode == 0);
816 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
817 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
818 styleElement->appendChild(childToAppend, exceptionCode);
819 ASSERT(exceptionCode == 0);
820 childToAppend = styleElement;
823 return childToAppend;
826 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
828 if (!textNode || !textNode->renderer() || start >= end)
831 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
832 InlineTextBox *box = textRenderer->firstTextBox();
834 // whole text node is empty
835 removeNode(textNode);
839 long length = textNode->length();
840 if (start >= length || end > length)
844 InlineTextBox *prevBox = 0;
845 DOMStringImpl *str = 0;
847 // This loop structure works to process all gaps preceding a box,
848 // and also will look at the gap after the last box.
849 while (prevBox || box) {
850 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
852 // No more chance for any intersections
855 int gapEnd = box ? box->m_start : length;
856 bool indicesIntersect = start <= gapEnd && end >= gapStart;
857 int gapLen = gapEnd - gapStart;
858 if (indicesIntersect && gapLen > 0) {
859 gapStart = kMax(gapStart, start);
860 gapEnd = kMin(gapEnd, end);
862 str = textNode->string()->substring(start, end - start);
865 // remove text in the gap
866 str->remove(gapStart - start - removed, gapLen);
872 box = box->nextTextBox();
876 // Replace the text between start and end with our pruned version.
878 replaceTextInNode(textNode, start, end - start, str);
881 // Assert that we are not going to delete all of the text in the node.
882 // If we were, that should have been done above with the call to
883 // removeNode and return.
884 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
885 deleteTextFromNode(textNode, start, end - start);
891 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
893 if (start.isNull() || end.isNull())
896 if (RangeImpl::compareBoundaryPoints(start, end) >= 0)
899 NodeImpl *node = start.node();
901 NodeImpl *next = node->traverseNextNode();
903 if (node->isTextNode()) {
904 TextImpl *textNode = static_cast<TextImpl *>(node);
905 bool isStartNode = node == start.node();
906 bool isEndNode = node == end.node();
907 int startOffset = isStartNode ? start.offset() : 0;
908 int endOffset = isEndNode ? end.offset() : textNode->length();
909 deleteInsignificantText(textNode, startOffset, endOffset);
912 if (node == end.node())
918 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
920 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
921 deleteInsignificantText(pos, end);
924 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
926 document()->updateLayout();
928 RenderObject *renderer = node->renderer();
929 if (!renderer->isBlockFlow())
932 if (renderer->height() > 0)
935 int exceptionCode = 0;
936 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
937 ASSERT(exceptionCode == 0);
938 breakNode->setAttribute(ATTR_CLASS, blockPlaceholderClassString());
939 appendNode(breakNode, node);
942 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
944 document()->updateLayout();
946 RenderObject *renderer = node->renderer();
947 if (!renderer->isBlockFlow())
950 // This code will remove a block placeholder if it still is at the end
951 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
952 // Of course, a person who hand-edits an HTML file could move a
953 // placeholder around, but it seems OK to be unconcerned about that case.
954 NodeImpl *last = node->lastChild();
955 if (last && last->isHTMLElement()) {
956 ElementImpl *element = static_cast<ElementImpl *>(last);
957 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
965 //==========================================================================================
967 //------------------------------------------------------------------------------------------
970 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
971 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
973 ASSERT(m_appendChild);
974 m_appendChild->ref();
976 ASSERT(m_parentNode);
980 AppendNodeCommand::~AppendNodeCommand()
982 ASSERT(m_appendChild);
983 m_appendChild->deref();
985 ASSERT(m_parentNode);
986 m_parentNode->deref();
989 void AppendNodeCommand::doApply()
991 ASSERT(m_appendChild);
992 ASSERT(m_parentNode);
994 int exceptionCode = 0;
995 m_parentNode->appendChild(m_appendChild, exceptionCode);
996 ASSERT(exceptionCode == 0);
999 void AppendNodeCommand::doUnapply()
1001 ASSERT(m_appendChild);
1002 ASSERT(m_parentNode);
1003 ASSERT(state() == Applied);
1005 int exceptionCode = 0;
1006 m_parentNode->removeChild(m_appendChild, exceptionCode);
1007 ASSERT(exceptionCode == 0);
1010 //------------------------------------------------------------------------------------------
1011 // ApplyStyleCommand
1013 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style)
1014 : CompositeEditCommand(document), m_style(style->makeMutable())
1020 ApplyStyleCommand::~ApplyStyleCommand()
1026 void ApplyStyleCommand::doApply()
1028 // apply the block-centric properties of the style
1029 CSSMutableStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
1031 applyBlockStyle(blockStyle);
1033 // apply any remaining styles to the inline elements
1034 // NOTE: hopefully, this string comparison is the same as checking for a non-null diff
1035 if (blockStyle->length() < m_style->length()) {
1036 CSSMutableStyleDeclarationImpl *inlineStyle = m_style->copy();
1038 blockStyle->diff(inlineStyle);
1039 applyInlineStyle(inlineStyle);
1040 inlineStyle->deref();
1043 blockStyle->deref();
1045 setEndingSelectionNeedsLayout();
1048 void ApplyStyleCommand::applyBlockStyle(CSSMutableStyleDeclarationImpl *style)
1050 // update document layout once before removing styles
1051 // so that we avoid the expense of updating before each and every call
1052 // to check a computed style
1053 document()->updateLayout();
1055 // get positions we want to use for applying style
1056 Position start(endingSelection().start());
1057 Position end(endingSelection().end());
1059 // remove current values, if any, of the specified styles from the blocks
1060 // NOTE: tracks the previous block to avoid repeated processing
1061 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1062 NodeImpl *prevBlock = 0;
1063 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1064 NodeImpl *block = node->enclosingBlockFlowElement();
1065 if (block != prevBlock && block->isHTMLElement()) {
1066 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1071 // apply specified styles to the block flow elements in the selected range
1073 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1074 NodeImpl *block = node->enclosingBlockFlowElement();
1075 if (block != prevBlock && block->isHTMLElement()) {
1076 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1082 void ApplyStyleCommand::applyInlineStyle(CSSMutableStyleDeclarationImpl *style)
1084 // adjust to the positions we want to use for applying style
1085 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1086 Position end(endingSelection().end().upstream(StayInBlock));
1088 // update document layout once before removing styles
1089 // so that we avoid the expense of updating before each and every call
1090 // to check a computed style
1091 document()->updateLayout();
1093 // Remove style from the selection.
1094 // Use the upstream position of the start for removing style.
1095 // This will ensure we remove all traces of the relevant styles from the selection
1096 // and prevent us from adding redundant ones, as described in:
1097 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1098 removeInlineStyle(style, start.upstream(), end);
1100 // split the start node if the selection starts inside of it
1101 bool splitStart = splitTextAtStartIfNeeded(start, end);
1103 start = endingSelection().start();
1104 end = endingSelection().end();
1107 // split the end node if the selection ends inside of it
1108 splitTextAtEndIfNeeded(start, end);
1109 start = endingSelection().start();
1110 end = endingSelection().end();
1112 // update document layout once before running the rest of the function
1113 // so that we avoid the expense of updating before each and every call
1114 // to check a computed style
1115 document()->updateLayout();
1117 if (start.node() == end.node()) {
1118 // simple case...start and end are the same node
1119 addInlineStyleIfNeeded(style, start.node(), end.node());
1122 NodeImpl *node = start.node();
1124 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1125 NodeImpl *runStart = node;
1127 NodeImpl *next = node->traverseNextNode();
1128 // Break if node is the end node, or if the next node does not fit in with
1129 // the current group.
1130 if (node == end.node() ||
1131 runStart->parentNode() != next->parentNode() ||
1132 (next->isHTMLElement() && next->id() != ID_BR) ||
1133 (next->renderer() && !next->renderer()->isInline()))
1137 // Now apply style to the run we found.
1138 addInlineStyleIfNeeded(style, runStart, node);
1140 if (node == end.node())
1142 node = node->traverseNextNode();
1147 //------------------------------------------------------------------------------------------
1148 // ApplyStyleCommand: style-removal helpers
1150 bool ApplyStyleCommand::isHTMLStyleNode(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1152 QValueListConstIterator<CSSProperty> end;
1153 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1154 switch ((*it).id()) {
1155 case CSS_PROP_FONT_WEIGHT:
1156 if (elem->id() == ID_B)
1159 case CSS_PROP_FONT_STYLE:
1160 if (elem->id() == ID_I)
1169 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1171 // This node can be removed.
1172 // EDIT FIXME: This does not handle the case where the node
1173 // has attributes. But how often do people add attributes to <B> tags?
1174 // Not so often I think.
1176 removeNodePreservingChildren(elem);
1179 void ApplyStyleCommand::removeCSSStyle(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1184 CSSMutableStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1188 QValueListConstIterator<CSSProperty> end;
1189 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1190 int propertyID = (*it).id();
1191 CSSValueImpl *value = decl->getPropertyCSSValue(propertyID);
1194 removeCSSProperty(decl, propertyID);
1199 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1200 // Check to see if the span is one we added to apply style.
1201 // If it is, and there are no more attributes on the span other than our
1202 // class marker, remove the span.
1203 if (decl->length() == 0) {
1204 removeNodeAttribute(elem, ATTR_STYLE);
1205 NamedAttrMapImpl *map = elem->attributes();
1206 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1207 removeNodePreservingChildren(elem);
1212 void ApplyStyleCommand::removeBlockStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1214 ASSERT(start.isNotNull());
1215 ASSERT(end.isNotNull());
1216 ASSERT(start.node()->inDocument());
1217 ASSERT(end.node()->inDocument());
1218 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1222 void ApplyStyleCommand::removeInlineStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1224 ASSERT(start.isNotNull());
1225 ASSERT(end.isNotNull());
1226 ASSERT(start.node()->inDocument());
1227 ASSERT(end.node()->inDocument());
1228 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1230 NodeImpl *node = start.node();
1232 NodeImpl *next = node->traverseNextNode();
1233 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1234 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1235 if (isHTMLStyleNode(style, elem))
1236 removeHTMLStyleNode(elem);
1238 removeCSSStyle(style, elem);
1240 if (node == end.node())
1246 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1250 Position pos = Position(node, node->childNodeCount()).upstream();
1251 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1252 RangeImpl::compareBoundaryPoints(pos, end) <= 0;
1255 //------------------------------------------------------------------------------------------
1256 // ApplyStyleCommand: style-application helpers
1259 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1261 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1262 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1263 TextImpl *text = static_cast<TextImpl *>(start.node());
1264 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1265 applyCommandToComposite(cmd);
1266 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1272 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1274 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1275 TextImpl *text = static_cast<TextImpl *>(end.node());
1276 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1277 EditCommandPtr cmd(impl);
1278 applyCommandToComposite(cmd);
1279 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1281 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1282 return impl->node()->previousSibling();
1287 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1293 NodeImpl *node = startNode;
1295 NodeImpl *next = node->traverseNextNode();
1296 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1298 appendNode(node, element);
1300 if (node == endNode)
1306 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *block)
1308 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1310 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1311 if (styleChange.cssStyle().length() > 0) {
1312 DOMString cssText = styleChange.cssStyle();
1313 CSSMutableStyleDeclarationImpl *decl = block->inlineStyleDecl();
1315 cssText += decl->cssText();
1316 block->setAttribute(ATTR_STYLE, cssText);
1320 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1322 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1323 // Both functions do similar work, and the common parts could be factored out.
1325 StyleChange styleChange(style, Position(startNode, 0));
1326 int exceptionCode = 0;
1328 if (styleChange.cssStyle().length() > 0) {
1329 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1330 ASSERT(exceptionCode == 0);
1331 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1332 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1333 insertNodeBefore(styleElement, startNode);
1334 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1337 if (styleChange.applyBold()) {
1338 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1339 ASSERT(exceptionCode == 0);
1340 insertNodeBefore(boldElement, startNode);
1341 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1344 if (styleChange.applyItalic()) {
1345 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1346 ASSERT(exceptionCode == 0);
1347 insertNodeBefore(italicElement, startNode);
1348 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1352 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1354 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1355 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1356 EditCommandPtr split(impl);
1358 pos = Position(impl->node(), 0);
1362 // EDIT FIXME: If modified to work with the internals of applying style,
1363 // this code can work to optimize cases where a style change is taking place on
1364 // a boundary between nodes where one of the nodes has the desired style. In other
1365 // words, it is possible for content to be merged into existing nodes rather than adding
1366 // additional markup.
1367 if (currentlyHasStyle(pos))
1371 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1372 NodeImpl *nextNode = pos.node()->traverseNextNode();
1374 Position next = Position(nextNode, 0);
1375 if (currentlyHasStyle(next))
1380 // try previous node
1381 if (pos.offset() <= pos.node()->caretMinOffset()) {
1382 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1384 Position prev = Position(prevNode, prevNode->maxOffset());
1385 if (currentlyHasStyle(prev))
1394 //------------------------------------------------------------------------------------------
1395 // DeleteFromTextNodeCommand
1397 DeleteFromTextNodeCommand::DeleteFromTextNodeCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1398 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1401 ASSERT(m_offset >= 0);
1402 ASSERT(m_offset < (long)m_node->length());
1403 ASSERT(m_count >= 0);
1408 DeleteFromTextNodeCommand::~DeleteFromTextNodeCommand()
1414 void DeleteFromTextNodeCommand::doApply()
1418 int exceptionCode = 0;
1419 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1420 ASSERT(exceptionCode == 0);
1422 m_node->deleteData(m_offset, m_count, exceptionCode);
1423 ASSERT(exceptionCode == 0);
1426 void DeleteFromTextNodeCommand::doUnapply()
1429 ASSERT(!m_text.isEmpty());
1431 int exceptionCode = 0;
1432 m_node->insertData(m_offset, m_text, exceptionCode);
1433 ASSERT(exceptionCode == 0);
1436 //------------------------------------------------------------------------------------------
1437 // DeleteSelectionCommand
1439 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1440 : CompositeEditCommand(document),
1441 m_hasSelectionToDelete(false),
1442 m_smartDelete(smartDelete),
1443 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1451 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1452 : CompositeEditCommand(document),
1453 m_hasSelectionToDelete(true),
1454 m_smartDelete(smartDelete),
1455 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1456 m_selectionToDelete(selection),
1464 void DeleteSelectionCommand::initializePositionData()
1467 // Handle setting some basic positions
1469 Position start = m_selectionToDelete.start();
1470 Position end = m_selectionToDelete.end();
1472 m_upstreamStart = start.upstream(StayInBlock);
1473 m_downstreamStart = start.downstream(StayInBlock);
1474 m_upstreamEnd = end.upstream(StayInBlock);
1475 m_downstreamEnd = end.downstream(StayInBlock);
1478 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
1480 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1481 bool hasLeadingWhitespaceBeforeAdjustment = m_leadingWhitespace.isNotNull();
1482 if (m_smartDelete && hasLeadingWhitespaceBeforeAdjustment) {
1483 Position pos = VisiblePosition(start).previous().deepEquivalent();
1484 // Expand out one character upstream for smart delete and recalculate
1485 // positions based on this change.
1486 m_upstreamStart = pos.upstream(StayInBlock);
1487 m_downstreamStart = pos.downstream(StayInBlock);
1488 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1490 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1491 // Note: trailing whitespace is only considered for smart delete if there is no leading
1492 // whitespace, as in the case where you double-click the first word of a paragraph.
1493 if (m_smartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_trailingWhitespace.isNotNull()) {
1494 // Expand out one character downstream for smart delete and recalculate
1495 // positions based on this change.
1496 Position pos = VisiblePosition(end).next().deepEquivalent();
1497 m_upstreamEnd = pos.upstream(StayInBlock);
1498 m_downstreamEnd = pos.downstream(StayInBlock);
1499 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1501 m_trailingWhitespaceValid = true;
1504 // Handle setting start and end blocks and the start node.
1506 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1507 m_startBlock->ref();
1508 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1510 m_startNode = m_upstreamStart.node();
1514 // Handle detecting if the line containing the selection end is itself fully selected.
1515 // This is one of the tests that determines if block merging of content needs to be done.
1517 VisiblePosition visibleEnd(end);
1518 if (isFirstVisiblePositionOnLine(visibleEnd)) {
1519 Position previousLineStart = previousLinePosition(visibleEnd, DOWNSTREAM, 0).deepEquivalent();
1520 if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
1521 m_mergeBlocksAfterDelete = false;
1524 debugPosition("m_upstreamStart ", m_upstreamStart);
1525 debugPosition("m_downstreamStart ", m_downstreamStart);
1526 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1527 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1528 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1529 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1530 debugNode( "m_startBlock ", m_startBlock);
1531 debugNode( "m_endBlock ", m_endBlock);
1532 debugNode( "m_startNode ", m_startNode);
1535 void DeleteSelectionCommand::saveTypingStyleState()
1537 // Figure out the typing style in effect before the delete is done.
1538 // FIXME: Improve typing style.
1539 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1540 CSSComputedStyleDeclarationImpl *computedStyle = m_selectionToDelete.start().computedStyle();
1541 computedStyle->ref();
1542 m_typingStyle = computedStyle->copyInheritableProperties();
1543 m_typingStyle->ref();
1544 computedStyle->deref();
1547 bool DeleteSelectionCommand::handleSpecialCaseAllContentDelete()
1549 Position start = m_downstreamStart;
1550 Position end = m_upstreamEnd;
1552 ElementImpl *rootElement = start.node()->rootEditableElement();
1553 Position rootStart = Position(rootElement, 0);
1554 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1555 if (start == VisiblePosition(rootStart).downstreamDeepEquivalent() && end == VisiblePosition(rootEnd).deepEquivalent()) {
1556 // Delete every child of the root editable element
1557 NodeImpl *node = rootElement->firstChild();
1559 NodeImpl *next = node->traverseNextSibling();
1568 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
1570 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1571 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1572 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1573 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1574 if (isBROnLineByItself) {
1575 removeNode(m_downstreamStart.node());
1576 m_endingPosition = m_upstreamStart;
1577 m_mergeBlocksAfterDelete = false;
1581 // Check for special-case where the selection contains only a BR right after a block ended.
1582 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1583 Position upstreamFromBR = m_downstreamEnd.upstream();
1584 bool startIsBRAfterBlock = downstreamEndIsBR && m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamFromBR.node()->enclosingBlockFlowElement();
1585 if (startIsBRAfterBlock) {
1586 removeNode(m_downstreamEnd.node());
1587 m_endingPosition = upstreamFromBR;
1588 m_mergeBlocksAfterDelete = false;
1592 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1593 // should not be done.
1594 if (upstreamStartIsBR && downstreamStartIsBR)
1595 m_mergeBlocksAfterDelete = false;
1600 void DeleteSelectionCommand::handleGeneralDelete()
1602 int startOffset = m_upstreamStart.offset();
1604 if (startOffset == 0 && m_startNode->isBlockFlow() && m_startBlock != m_endBlock && !m_endBlock->isAncestor(m_startBlock)) {
1605 // The block containing the start of the selection is completely selected.
1606 // Delete it all in one step right here.
1607 ASSERT(!m_downstreamEnd.node()->isAncestor(m_startNode));
1609 // shift the start node to the start of the next block.
1610 NodeImpl *old = m_startNode;
1611 m_startNode = m_startBlock->traverseNextSibling();
1616 removeFullySelectedNode(m_startBlock);
1618 else if (startOffset >= m_startNode->caretMaxOffset()) {
1619 // Move the start node to the next node in the tree since the startOffset is equal to
1620 // or beyond the start node's caretMaxOffset This means there is nothing visible to delete.
1621 // However, before moving on, delete any insignificant text that may be present in a text node.
1622 if (m_startNode->isTextNode()) {
1623 // Delete any insignificant text from this node.
1624 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1625 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1626 deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1629 // shift the start node to the next
1630 NodeImpl *old = m_startNode;
1631 m_startNode = old->traverseNextNode();
1637 if (m_startNode == m_downstreamEnd.node()) {
1638 // The selection to delete is all in one node.
1639 if (!m_startNode->renderer() ||
1640 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1642 removeFullySelectedNode(m_startNode);
1644 else if (m_downstreamEnd.offset() - startOffset > 0) {
1645 // in a text node that needs to be trimmed
1646 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1647 deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
1648 m_trailingWhitespaceValid = false;
1652 // The selection to delete spans more than one node.
1653 NodeImpl *node = m_startNode;
1655 if (startOffset > 0) {
1656 // in a text node that needs to be trimmed
1657 TextImpl *text = static_cast<TextImpl *>(node);
1658 deleteTextFromNode(text, startOffset, text->length() - startOffset);
1659 node = node->traverseNextNode();
1662 // handle deleting all nodes that are completely selected
1663 while (node && node != m_downstreamEnd.node()) {
1664 if (!m_downstreamEnd.node()->isAncestor(node)) {
1665 NodeImpl *nextNode = node->traverseNextSibling();
1666 removeFullySelectedNode(node);
1670 NodeImpl *n = node->lastChild();
1671 while (n && n->lastChild())
1673 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1674 // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
1675 removeFullySelectedNode(node);
1676 m_trailingWhitespaceValid = false;
1680 node = node->traverseNextNode();
1685 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1686 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1687 // need to delete whole node
1688 // we can get here if this is the last node in the block
1689 removeFullySelectedNode(m_downstreamEnd.node());
1690 m_trailingWhitespaceValid = false;
1693 // in a text node that needs to be trimmed
1694 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1695 if (m_downstreamEnd.offset() > 0) {
1696 deleteTextFromNode(text, 0, m_downstreamEnd.offset());
1697 m_downstreamEnd = Position(text, 0);
1698 m_trailingWhitespaceValid = false;
1705 void DeleteSelectionCommand::fixupWhitespace()
1707 document()->updateLayout();
1708 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1709 LOG(Editing, "replace leading");
1710 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1711 replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1713 else if (m_trailingWhitespace.isNotNull()) {
1714 if (m_trailingWhitespaceValid) {
1715 if (!m_trailingWhitespace.isRenderedCharacter()) {
1716 LOG(Editing, "replace trailing [valid]");
1717 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1718 replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1722 Position pos = m_endingPosition.downstream(StayInBlock);
1723 pos = Position(pos.node(), pos.offset() - 1);
1724 if (isWS(pos) && !pos.isRenderedCharacter()) {
1725 LOG(Editing, "replace trailing [invalid]");
1726 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1727 replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
1728 // need to adjust ending position since the trailing position is not valid.
1729 m_endingPosition = pos;
1735 // This function moves nodes in the block containing startNode to dstBlock, starting
1736 // from startNode and proceeding to the end of the block. Nodes in the block containing
1737 // startNode that appear in document order before startNode are not moved.
1738 // This function is an important helper for deleting selections that cross block
1740 void DeleteSelectionCommand::moveNodesAfterNode()
1742 if (!m_mergeBlocksAfterDelete)
1745 if (m_endBlock == m_startBlock)
1748 NodeImpl *startNode = m_downstreamEnd.node();
1749 NodeImpl *dstNode = m_upstreamStart.node();
1751 if (!startNode->inDocument() || !dstNode->inDocument())
1754 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1755 if (isTableStructureNode(startBlock))
1756 // Do not move content between parts of a table
1759 // Now that we are about to add content, check to see if a placeholder element
1761 removeBlockPlaceholderIfNeeded(startBlock);
1763 // Move the subtree containing node
1764 NodeImpl *node = startNode->enclosingInlineElement();
1766 // Insert after the subtree containing destNode
1767 NodeImpl *refNode = dstNode->enclosingInlineElement();
1769 // Nothing to do if start is already at the beginning of dstBlock
1770 NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
1771 if (startBlock == dstBlock->firstChild())
1775 while (node && node->isAncestor(startBlock)) {
1776 NodeImpl *moveNode = node;
1777 node = node->nextSibling();
1778 removeNode(moveNode);
1779 insertNodeAfter(moveNode, refNode);
1783 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1784 // to make the layout come out right. Consider this document:
1790 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1791 // move the contents of the div to the block containing 'One' and delete the div.
1792 // This will have the side effect of moving 'Three' on to the same line as 'One'
1793 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1794 // This may not be ideal, but it is better than nothing.
1795 document()->updateLayout();
1796 if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
1797 removeNode(startBlock);
1798 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1799 int exceptionCode = 0;
1800 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1801 ASSERT(exceptionCode == 0);
1802 insertNodeAfter(breakNode, refNode);
1807 void DeleteSelectionCommand::calculateEndingPosition()
1809 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1812 m_endingPosition = m_upstreamStart;
1813 if (m_endingPosition.node()->inDocument())
1816 m_endingPosition = m_downstreamEnd;
1817 if (m_endingPosition.node()->inDocument())
1820 m_endingPosition = Position(m_startBlock, 0);
1821 if (m_endingPosition.node()->inDocument())
1824 m_endingPosition = Position(m_endBlock, 0);
1825 if (m_endingPosition.node()->inDocument())
1828 m_endingPosition = Position(document()->documentElement(), 0);
1831 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1833 // Compute the difference between the style before the delete and the style now
1834 // after the delete has been done. Set this style on the part, so other editing
1835 // commands being composed with this one will work, and also cache it on the command,
1836 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1838 // FIXME: Improve typing style.
1839 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1840 if (m_startNode == m_endingPosition.node())
1841 document()->part()->setTypingStyle(0);
1843 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1844 endingStyle.diff(m_typingStyle);
1845 if (!m_typingStyle->length()) {
1846 m_typingStyle->deref();
1849 document()->part()->setTypingStyle(m_typingStyle);
1850 setTypingStyle(m_typingStyle);
1854 void DeleteSelectionCommand::clearTransientState()
1856 m_selectionToDelete.clear();
1857 m_upstreamStart.clear();
1858 m_downstreamStart.clear();
1859 m_upstreamEnd.clear();
1860 m_downstreamEnd.clear();
1861 m_endingPosition.clear();
1862 m_leadingWhitespace.clear();
1863 m_trailingWhitespace.clear();
1866 m_startBlock->deref();
1870 m_endBlock->deref();
1874 m_startNode->deref();
1877 if (m_typingStyle) {
1878 m_typingStyle->deref();
1883 void DeleteSelectionCommand::doApply()
1885 // If selection has not been set to a custom selection when the command was created,
1886 // use the current ending selection.
1887 if (!m_hasSelectionToDelete)
1888 m_selectionToDelete = endingSelection();
1890 if (!m_selectionToDelete.isRange())
1893 initializePositionData();
1895 if (!m_startBlock || !m_endBlock) {
1896 // Can't figure out what blocks we're in. This can happen if
1897 // the document structure is not what we are expecting, like if
1898 // the document has no body element, or if the editable block
1899 // has been changed to display: inline. Some day it might
1900 // be nice to be able to deal with this, but for now, bail.
1901 clearTransientState();
1905 // Delete any text that may hinder our ability to fixup whitespace after the detele
1906 deleteInsignificantTextDownstream(m_trailingWhitespace);
1908 saveTypingStyleState();
1910 if (!handleSpecialCaseAllContentDelete())
1911 if (!handleSpecialCaseBRDelete())
1912 handleGeneralDelete();
1914 // Do block merge if start and end of selection are in different blocks.
1915 moveNodesAfterNode();
1917 calculateEndingPosition();
1920 // If the delete emptied a block, add in a placeholder so the block does not
1921 // seem to disappear.
1922 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1923 calculateTypingStyleAfterDelete();
1924 setEndingSelection(m_endingPosition);
1925 debugPosition("endingPosition ", m_endingPosition);
1926 clearTransientState();
1927 rebalanceWhitespace();
1930 bool DeleteSelectionCommand::preservesTypingStyle() const
1935 //------------------------------------------------------------------------------------------
1936 // InsertIntoTextNode
1938 InsertIntoTextNode::InsertIntoTextNode(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
1939 : EditCommand(document), m_node(node), m_offset(offset)
1942 ASSERT(m_offset >= 0);
1943 ASSERT(!text.isEmpty());
1946 m_text = text.copy(); // make a copy to ensure that the string never changes
1949 InsertIntoTextNode::~InsertIntoTextNode()
1955 void InsertIntoTextNode::doApply()
1958 ASSERT(m_offset >= 0);
1959 ASSERT(!m_text.isEmpty());
1961 int exceptionCode = 0;
1962 m_node->insertData(m_offset, m_text, exceptionCode);
1963 ASSERT(exceptionCode == 0);
1966 void InsertIntoTextNode::doUnapply()
1969 ASSERT(m_offset >= 0);
1970 ASSERT(!m_text.isEmpty());
1972 int exceptionCode = 0;
1973 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
1974 ASSERT(exceptionCode == 0);
1977 //------------------------------------------------------------------------------------------
1978 // InsertLineBreakCommand
1980 InsertLineBreakCommand::InsertLineBreakCommand(DocumentImpl *document)
1981 : CompositeEditCommand(document)
1985 void InsertLineBreakCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
1987 // Insert the BR after the caret position. In the case the
1988 // position is a block, do an append. We don't want to insert
1989 // the BR *after* the block.
1990 Position upstream(pos.upstream(StayInBlock));
1991 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1992 if (cb == pos.node())
1993 appendNode(node, cb);
1995 insertNodeAfter(node, pos.node());
1998 void InsertLineBreakCommand::insertNodeBeforePosition(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 *before* the block.
2003 Position upstream(pos.upstream(StayInBlock));
2004 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2005 if (cb == pos.node())
2006 appendNode(node, cb);
2008 insertNodeBefore(node, pos.node());
2011 void InsertLineBreakCommand::doApply()
2014 Selection selection = endingSelection();
2016 int exceptionCode = 0;
2017 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
2018 ASSERT(exceptionCode == 0);
2020 NodeImpl *nodeToInsert = breakNode;
2022 // Handle the case where there is a typing style.
2023 // FIXME: Improve typing style.
2024 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2025 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2026 if (typingStyle && typingStyle->length() > 0)
2027 nodeToInsert = applyTypingStyle(breakNode);
2029 Position pos(selection.start().upstream(StayInBlock));
2030 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
2031 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
2032 bool atEndOfBlock = isLastVisiblePositionInBlock(VisiblePosition(pos));
2035 LOG(Editing, "input newline case 1");
2036 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
2037 // This makes the "real" BR we want to insert appear in the rendering without any
2038 // significant side effects (and no real worries either since you can't arrow past
2040 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
2041 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
2042 insertNodeBefore(nodeToInsert, pos.node());
2045 NodeImpl *next = pos.node()->traverseNextNode();
2046 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
2047 insertNodeAfterPosition(nodeToInsert, pos);
2048 if (hasTrailingBR) {
2049 setEndingSelection(Position(next, 0));
2051 else if (!document()->inStrictMode()) {
2052 // Insert an "extra" BR at the end of the block.
2053 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
2054 ASSERT(exceptionCode == 0);
2055 insertNodeAfter(extraBreakNode, nodeToInsert);
2056 setEndingSelection(Position(extraBreakNode, 0));
2061 LOG(Editing, "input newline case 2");
2062 // Insert node before downstream position, and place caret there as well.
2063 Position endingPosition = pos.downstream(StayInBlock);
2064 insertNodeBeforePosition(nodeToInsert, endingPosition);
2065 setEndingSelection(endingPosition);
2068 LOG(Editing, "input newline case 3");
2069 // Insert BR after this node. Place caret in the position that is downstream
2070 // of the current position, reckoned before inserting the BR in between.
2071 Position endingPosition = pos.downstream(StayInBlock);
2072 insertNodeAfterPosition(nodeToInsert, pos);
2073 setEndingSelection(endingPosition);
2076 // Split a text node
2077 LOG(Editing, "input newline case 4");
2078 ASSERT(pos.node()->isTextNode());
2081 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2082 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
2083 deleteTextFromNode(textNode, 0, pos.offset());
2084 insertNodeBefore(textBeforeNode, textNode);
2085 insertNodeBefore(nodeToInsert, textNode);
2086 Position endingPosition = Position(textNode, 0);
2088 // Handle whitespace that occurs after the split
2089 document()->updateLayout();
2090 if (!endingPosition.isRenderedCharacter()) {
2091 // Clear out all whitespace and insert one non-breaking space
2092 deleteInsignificantTextDownstream(endingPosition);
2093 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
2096 setEndingSelection(endingPosition);
2098 rebalanceWhitespace();
2101 //------------------------------------------------------------------------------------------
2102 // InsertNodeBeforeCommand
2104 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2105 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2107 ASSERT(m_insertChild);
2108 m_insertChild->ref();
2114 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2116 ASSERT(m_insertChild);
2117 m_insertChild->deref();
2120 m_refChild->deref();
2123 void InsertNodeBeforeCommand::doApply()
2125 ASSERT(m_insertChild);
2127 ASSERT(m_refChild->parentNode());
2129 int exceptionCode = 0;
2130 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2131 ASSERT(exceptionCode == 0);
2134 void InsertNodeBeforeCommand::doUnapply()
2136 ASSERT(m_insertChild);
2138 ASSERT(m_refChild->parentNode());
2140 int exceptionCode = 0;
2141 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2142 ASSERT(exceptionCode == 0);
2145 //------------------------------------------------------------------------------------------
2146 // InsertParagraphSeparatorCommand
2148 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(DocumentImpl *document)
2149 : CompositeEditCommand(document)
2153 InsertParagraphSeparatorCommand::~InsertParagraphSeparatorCommand()
2155 derefNodesInList(clonedNodes);
2158 void InsertParagraphSeparatorCommand::doApply()
2160 Selection selection = endingSelection();
2161 if (selection.isNone())
2164 // Delete the current selection.
2165 // If the selection is a range and the start and end nodes are in different blocks,
2166 // then this command bails after the delete, but takes the one additional step of
2167 // moving the selection downstream so it is in the ending block (if that block is
2168 // still around, that is).
2169 Position pos = selection.start();
2170 if (selection.isRange()) {
2171 NodeImpl *startBlockBeforeDelete = selection.start().node()->enclosingBlockFlowElement();
2172 NodeImpl *endBlockBeforeDelete = selection.end().node()->enclosingBlockFlowElement();
2173 bool doneAfterDelete = startBlockBeforeDelete != endBlockBeforeDelete;
2174 deleteSelection(false, false);
2175 if (doneAfterDelete) {
2176 document()->updateLayout();
2177 setEndingSelection(endingSelection().start().downstream());
2178 rebalanceWhitespace();
2181 pos = endingSelection().start().upstream();
2184 // Find the start block.
2185 NodeImpl *startNode = pos.node();
2186 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
2187 if (!startBlock || !startBlock->parentNode())
2190 // Build up list of ancestors in between the start node and the start block.
2191 for (NodeImpl *n = startNode->parentNode(); n && n != startBlock; n = n->parentNode())
2192 ancestors.prepend(n);
2194 // Make new block to represent the newline.
2195 // If the start block is the body, just make a P tag, otherwise, make a shallow clone
2196 // of the the start block.
2197 NodeImpl *addedBlock = 0;
2198 if (startBlock->id() == ID_BODY) {
2199 int exceptionCode = 0;
2200 addedBlock = document()->createHTMLElement("P", exceptionCode);
2201 ASSERT(exceptionCode == 0);
2202 appendNode(addedBlock, startBlock);
2205 addedBlock = startBlock->cloneNode(false);
2206 insertNodeAfter(addedBlock, startBlock);
2209 insertBlockPlaceholderIfNeeded(addedBlock);
2210 clonedNodes.append(addedBlock);
2212 if (!isLastVisiblePositionInNode(VisiblePosition(pos), startBlock)) {
2213 // Split at pos if in the middle of a text node.
2214 if (startNode->isTextNode()) {
2215 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2216 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2217 if (pos.offset() > 0 && !atEnd) {
2218 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2219 EditCommandPtr cmd(splitCommand);
2220 applyCommandToComposite(cmd);
2221 startNode = splitCommand->node();
2222 pos = Position(startNode, 0);
2225 startNode = startNode->traverseNextNode();
2229 else if (pos.offset() > 0) {
2230 startNode = startNode->traverseNextNode();
2234 // Make clones of ancestors in between the start node and the start block.
2235 NodeImpl *parent = addedBlock;
2236 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2237 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2239 clonedNodes.append(child);
2240 appendNode(child, parent);
2244 // Move the start node and the siblings of the start node.
2245 NodeImpl *n = startNode;
2246 if (n->id() == ID_BR)
2247 n = n->nextSibling();
2248 while (n && n != addedBlock) {
2249 NodeImpl *next = n->nextSibling();
2251 appendNode(n, parent);
2255 // Move everything after the start node.
2256 NodeImpl *leftParent = ancestors.last();
2257 while (leftParent && leftParent != startBlock) {
2258 parent = parent->parentNode();
2259 NodeImpl *n = leftParent->nextSibling();
2261 NodeImpl *next = n->nextSibling();
2263 appendNode(n, parent);
2266 leftParent = leftParent->parentNode();
2270 // Put the selection right at the start of the added block.
2271 setEndingSelection(Position(addedBlock, 0));
2272 rebalanceWhitespace();
2275 //------------------------------------------------------------------------------------------
2276 // InsertParagraphSeparatorInQuotedContentCommand
2278 InsertParagraphSeparatorInQuotedContentCommand::InsertParagraphSeparatorInQuotedContentCommand(DocumentImpl *document)
2279 : CompositeEditCommand(document)
2283 InsertParagraphSeparatorInQuotedContentCommand::~InsertParagraphSeparatorInQuotedContentCommand()
2285 derefNodesInList(clonedNodes);
2287 m_breakNode->deref();
2290 bool InsertParagraphSeparatorInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
2292 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
2295 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
2298 void InsertParagraphSeparatorInQuotedContentCommand::doApply()
2300 Selection selection = endingSelection();
2301 if (selection.isNone())
2304 // Delete the current selection.
2305 Position pos = selection.start();
2306 if (selection.isRange()) {
2307 deleteSelection(false, false);
2308 pos = endingSelection().start().upstream();
2311 // Find the top-most blockquote from the start.
2312 NodeImpl *startNode = pos.node();
2313 NodeImpl *topBlockquote = 0;
2314 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
2315 if (isMailBlockquote(n))
2318 if (!topBlockquote || !topBlockquote->parentNode())
2321 // Build up list of ancestors in between the start node and the top blockquote.
2322 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
2323 ancestors.prepend(n);
2325 // Insert a break after the top blockquote.
2326 int exceptionCode = 0;
2327 m_breakNode = document()->createHTMLElement("BR", exceptionCode);
2329 ASSERT(exceptionCode == 0);
2330 insertNodeAfter(m_breakNode, topBlockquote);
2332 if (!isLastVisiblePositionInNode(VisiblePosition(pos), topBlockquote)) {
2333 // Split at pos if in the middle of a text node.
2334 if (startNode->isTextNode()) {
2335 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2336 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2337 if (pos.offset() > 0 && !atEnd) {
2338 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2339 EditCommandPtr cmd(splitCommand);
2340 applyCommandToComposite(cmd);
2341 startNode = splitCommand->node();
2342 pos = Position(startNode, 0);
2345 startNode = startNode->traverseNextNode();
2349 else if (pos.offset() > 0) {
2350 startNode = startNode->traverseNextNode();
2354 // Insert a clone of the top blockquote after the break.
2355 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2356 clonedBlockquote->ref();
2357 insertBlockPlaceholderIfNeeded(clonedBlockquote);
2358 clonedNodes.append(clonedBlockquote);
2359 insertNodeAfter(clonedBlockquote, m_breakNode);
2361 // Make clones of ancestors in between the start node and the top blockquote.
2362 NodeImpl *parent = clonedBlockquote;
2363 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2364 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2366 clonedNodes.append(child);
2367 appendNode(child, parent);
2371 // Move the start node and the siblings of the start node.
2372 NodeImpl *n = startNode;
2373 bool startIsBR = n->id() == ID_BR;
2375 n = n->nextSibling();
2377 NodeImpl *next = n->nextSibling();
2379 appendNode(n, parent);
2383 // Move everything after the start node.
2384 NodeImpl *leftParent = ancestors.last();
2388 leftParent = topBlockquote;
2389 ElementImpl *b = document()->createHTMLElement("BR", exceptionCode);
2391 clonedNodes.append(b);
2392 ASSERT(exceptionCode == 0);
2393 appendNode(b, leftParent);
2396 leftParent = ancestors.last();
2397 while (leftParent && leftParent != topBlockquote) {
2398 parent = parent->parentNode();
2399 NodeImpl *n = leftParent->nextSibling();
2401 NodeImpl *next = n->nextSibling();
2403 appendNode(n, parent);
2406 leftParent = leftParent->parentNode();
2410 // Put the selection right before the break.
2411 setEndingSelection(Position(m_breakNode, 0));
2412 rebalanceWhitespace();
2415 //------------------------------------------------------------------------------------------
2416 // InsertTextCommand
2418 InsertTextCommand::InsertTextCommand(DocumentImpl *document)
2419 : CompositeEditCommand(document), m_charactersAdded(0)
2423 void InsertTextCommand::doApply()
2427 void InsertTextCommand::deleteCharacter()
2429 ASSERT(state() == Applied);
2431 Selection selection = endingSelection();
2433 if (!selection.start().node()->isTextNode())
2436 int exceptionCode = 0;
2437 int offset = selection.start().offset() - 1;
2438 if (offset >= selection.start().node()->caretMinOffset()) {
2439 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2440 textNode->deleteData(offset, 1, exceptionCode);
2441 ASSERT(exceptionCode == 0);
2442 selection = Selection(Position(textNode, offset));
2443 setEndingSelection(selection);
2444 m_charactersAdded--;
2448 Position InsertTextCommand::prepareForTextInsertion(bool adjustDownstream)
2450 // Prepare for text input by looking at the current position.
2451 // It may be necessary to insert a text node to receive characters.
2452 Selection selection = endingSelection();
2453 ASSERT(selection.isCaret());
2455 Position pos = selection.start();
2456 if (adjustDownstream)
2457 pos = pos.downstream(StayInBlock);
2459 pos = pos.upstream(StayInBlock);
2461 if (!pos.node()->isTextNode()) {
2462 NodeImpl *textNode = document()->createEditingTextNode("");
2463 NodeImpl *nodeToInsert = textNode;
2465 // Handle the case where there is a typing style.
2466 // FIXME: Improve typing style.
2467 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2468 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2469 if (typingStyle && typingStyle->length() > 0)
2470 nodeToInsert = applyTypingStyle(textNode);
2472 // Now insert the node in the right place
2473 if (pos.node()->isEditableBlock()) {
2474 LOG(Editing, "prepareForTextInsertion case 1");
2475 appendNode(nodeToInsert, pos.node());
2477 else if (pos.node()->caretMinOffset() == pos.offset()) {
2478 LOG(Editing, "prepareForTextInsertion case 2");
2479 insertNodeBefore(nodeToInsert, pos.node());
2481 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2482 LOG(Editing, "prepareForTextInsertion case 3");
2483 insertNodeAfter(nodeToInsert, pos.node());
2486 ASSERT_NOT_REACHED();
2488 pos = Position(textNode, 0);
2491 // Handle the case where there is a typing style.
2492 // FIXME: Improve typing style.
2493 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2494 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2495 if (typingStyle && typingStyle->length() > 0) {
2496 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2497 // Need to split current text node in order to insert a span.
2498 TextImpl *text = static_cast<TextImpl *>(pos.node());
2499 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2500 EditCommandPtr cmd(impl);
2501 applyCommandToComposite(cmd);
2502 setEndingSelection(Position(impl->node(), 0));
2505 TextImpl *editingTextNode = document()->createEditingTextNode("");
2506 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2507 if (node->isBlockFlow())
2508 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2510 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2511 pos = Position(editingTextNode, 0);
2517 void InsertTextCommand::input(const DOMString &text, bool selectInsertedText)
2519 Selection selection = endingSelection();
2520 bool adjustDownstream = isFirstVisiblePositionOnLine(VisiblePosition(selection.start().downstream(StayInBlock)));
2522 // Delete the current selection, or collapse whitespace, as needed
2523 if (selection.isRange())
2526 // Delete any insignificant text that could get in the way of whitespace turning
2527 // out correctly after the insertion.
2528 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2530 // Make sure the document is set up to receive text
2531 Position pos = prepareForTextInsertion(adjustDownstream);
2533 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2534 long offset = pos.offset();
2536 // Now that we are about to add content, check to see if a placeholder element
2538 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2540 // These are temporary implementations for inserting adjoining spaces
2541 // into a document. We are working on a CSS-related whitespace solution
2542 // that will replace this some day. We hope.
2544 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2545 // although the number of spaces varies (we choose four spaces).
2546 // Note that there is no attempt to make this work like a real tab stop, it is merely
2547 // a set number of spaces. This also seems to be the HTML editing convention.
2548 for (int i = 0; i < spacesPerTab; i++) {
2549 insertSpace(textNode, offset);
2550 rebalanceWhitespace();
2551 document()->updateLayout();
2553 if (selectInsertedText)
2554 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2556 setEndingSelection(Position(textNode, offset + spacesPerTab));
2557 m_charactersAdded += spacesPerTab;
2559 else if (isWS(text)) {
2560 insertSpace(textNode, offset);
2561 if (selectInsertedText)
2562 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2564 setEndingSelection(Position(textNode, offset + 1));
2565 m_charactersAdded++;
2566 rebalanceWhitespace();
2569 const DOMString &existingText = textNode->data();
2570 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2571 // DOM looks like this:
2572 // character nbsp caret
2573 // As we are about to insert a non-whitespace character at the caret
2574 // convert the nbsp to a regular space.
2575 // EDIT FIXME: This needs to be improved some day to convert back only
2576 // those nbsp's added by the editor to make rendering come out right.
2577 replaceTextInNode(textNode, offset - 1, 1, " ");
2579 insertTextIntoNode(textNode, offset, text);
2580 if (selectInsertedText)
2581 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2583 setEndingSelection(Position(textNode, offset + text.length()));
2584 m_charactersAdded += text.length();
2588 void InsertTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2592 DOMString text(textNode->data());
2594 // count up all spaces and newlines in front of the caret
2595 // delete all collapsed ones
2596 // this will work out OK since the offset we have been passed has been upstream-ized
2598 for (unsigned int i = offset; i < text.length(); i++) {
2605 // By checking the character at the downstream position, we can
2606 // check if there is a rendered WS at the caret
2607 Position pos(textNode, offset);
2608 Position downstream = pos.downstream();
2609 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2610 count--; // leave this WS in
2612 deleteTextFromNode(textNode, offset, count);
2615 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2616 // insert a "regular" space
2617 insertTextIntoNode(textNode, offset, " ");
2621 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2622 // DOM looks like this:
2624 // insert a space between the two nbsps
2625 insertTextIntoNode(textNode, offset - 1, " ");
2630 insertTextIntoNode(textNode, offset, nonBreakingSpaceString());
2633 bool InsertTextCommand::isInsertTextCommand() const
2638 //------------------------------------------------------------------------------------------
2639 // JoinTextNodesCommand
2641 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2642 : EditCommand(document), m_text1(text1), m_text2(text2)
2646 ASSERT(m_text1->nextSibling() == m_text2);
2647 ASSERT(m_text1->length() > 0);
2648 ASSERT(m_text2->length() > 0);
2654 JoinTextNodesCommand::~JoinTextNodesCommand()
2662 void JoinTextNodesCommand::doApply()
2666 ASSERT(m_text1->nextSibling() == m_text2);
2668 int exceptionCode = 0;
2669 m_text2->insertData(0, m_text1->data(), exceptionCode);
2670 ASSERT(exceptionCode == 0);
2672 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2673 ASSERT(exceptionCode == 0);
2675 m_offset = m_text1->length();
2678 void JoinTextNodesCommand::doUnapply()
2681 ASSERT(m_offset > 0);
2683 int exceptionCode = 0;
2685 m_text2->deleteData(0, m_offset, exceptionCode);
2686 ASSERT(exceptionCode == 0);
2688 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2689 ASSERT(exceptionCode == 0);
2691 ASSERT(m_text2->previousSibling()->isTextNode());
2692 ASSERT(m_text2->previousSibling() == m_text1);
2695 //------------------------------------------------------------------------------------------
2696 // MoveSelectionCommand
2698 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2699 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2705 MoveSelectionCommand::~MoveSelectionCommand()
2708 m_fragment->deref();
2711 void MoveSelectionCommand::doApply()
2713 Selection selection = endingSelection();
2714 ASSERT(selection.isRange());
2716 // Update the position otherwise it may become invalid after the selection is deleted.
2717 NodeImpl *positionNode = m_position.node();
2718 long positionOffset = m_position.offset();
2719 Position selectionEnd = selection.end();
2720 long selectionEndOffset = selectionEnd.offset();
2721 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2722 positionOffset -= selectionEndOffset;
2723 Position selectionStart = selection.start();
2724 if (selectionStart.node() == positionNode) {
2725 positionOffset += selectionStart.offset();
2729 deleteSelection(m_smartMove);
2731 setEndingSelection(Position(positionNode, positionOffset));
2732 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2733 applyCommandToComposite(cmd);
2736 //------------------------------------------------------------------------------------------
2737 // RebalanceWhitespaceCommand
2739 RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(DocumentImpl *document, const Position &pos)
2740 : EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset), m_downstreamOffset(InvalidOffset)
2744 RebalanceWhitespaceCommand::~RebalanceWhitespaceCommand()
2748 void RebalanceWhitespaceCommand::doApply()
2750 static DOMString space(" ");
2752 if (m_position.isNull() || !m_position.node()->isTextNode())
2755 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2756 DOMString text = textNode->data();
2757 if (text.length() == 0)
2760 // find upstream offset
2761 long upstream = m_position.offset();
2762 while (upstream > 0 && isWS(text[upstream - 1]) || isNBSP(text[upstream - 1])) {
2764 m_upstreamOffset = upstream;
2767 // find downstream offset
2768 long downstream = m_position.offset();
2769 while ((unsigned)downstream < text.length() && isWS(text[downstream]) || isNBSP(text[downstream])) {
2771 m_downstreamOffset = downstream;
2774 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2777 m_upstreamOffset = upstream;
2778 m_downstreamOffset = downstream;
2779 long length = m_downstreamOffset - m_upstreamOffset;
2781 m_beforeString = text.substring(m_upstreamOffset, length);
2783 // The following loop figures out a "rebalanced" whitespace string for any length
2784 // string, and takes into account the special cases that need to handled for the
2785 // start and end of strings (i.e. first and last character must be an nbsp.
2786 long i = m_upstreamOffset;
2787 while (i < m_downstreamOffset) {
2788 long add = (m_downstreamOffset - i) % 3;
2791 m_afterString += nonBreakingSpaceString();
2792 m_afterString += space;
2793 m_afterString += nonBreakingSpaceString();
2797 if (i == 0 || (unsigned)i + 1 == text.length()) // at start or end of string
2798 m_afterString += nonBreakingSpaceString();
2800 m_afterString += space;
2803 if ((unsigned)i + 2 == text.length()) {
2805 m_afterString += nonBreakingSpaceString();
2806 m_afterString += nonBreakingSpaceString();
2809 m_afterString += nonBreakingSpaceString();
2810 m_afterString += space;
2817 text.remove(m_upstreamOffset, length);
2818 text.insert(m_afterString, m_upstreamOffset);
2821 void RebalanceWhitespaceCommand::doUnapply()
2823 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2826 ASSERT(m_position.node()->isTextNode());
2827 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2828 DOMString text = textNode->data();
2829 text.remove(m_upstreamOffset, m_afterString.length());
2830 text.insert(m_beforeString, m_upstreamOffset);
2833 bool RebalanceWhitespaceCommand::preservesTypingStyle() const
2838 //------------------------------------------------------------------------------------------
2839 // RemoveCSSPropertyCommand
2841 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2842 : EditCommand(document), m_decl(decl->makeMutable()), m_property(property), m_important(false)
2848 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
2854 void RemoveCSSPropertyCommand::doApply()
2858 m_oldValue = m_decl->getPropertyValue(m_property);
2859 ASSERT(!m_oldValue.isNull());
2861 m_important = m_decl->getPropertyPriority(m_property);
2862 m_decl->removeProperty(m_property);
2865 void RemoveCSSPropertyCommand::doUnapply()
2868 ASSERT(!m_oldValue.isNull());
2870 m_decl->setProperty(m_property, m_oldValue, m_important);
2873 //------------------------------------------------------------------------------------------
2874 // RemoveNodeAttributeCommand
2876 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
2877 : EditCommand(document), m_element(element), m_attribute(attribute)
2883 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
2889 void RemoveNodeAttributeCommand::doApply()
2893 m_oldValue = m_element->getAttribute(m_attribute);
2894 ASSERT(!m_oldValue.isNull());
2896 int exceptionCode = 0;
2897 m_element->removeAttribute(m_attribute, exceptionCode);
2898 ASSERT(exceptionCode == 0);
2901 void RemoveNodeAttributeCommand::doUnapply()
2904 ASSERT(!m_oldValue.isNull());
2906 int exceptionCode = 0;
2907 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2908 ASSERT(exceptionCode == 0);
2911 //------------------------------------------------------------------------------------------
2912 // RemoveNodeCommand
2914 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
2915 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
2917 ASSERT(m_removeChild);
2918 m_removeChild->ref();
2920 m_parent = m_removeChild->parentNode();
2924 m_refChild = m_removeChild->nextSibling();
2929 RemoveNodeCommand::~RemoveNodeCommand()
2934 ASSERT(m_removeChild);
2935 m_removeChild->deref();
2938 m_refChild->deref();
2941 void RemoveNodeCommand::doApply()
2944 ASSERT(m_removeChild);
2946 int exceptionCode = 0;
2947 m_parent->removeChild(m_removeChild, exceptionCode);
2948 ASSERT(exceptionCode == 0);
2951 void RemoveNodeCommand::doUnapply()
2954 ASSERT(m_removeChild);
2956 int exceptionCode = 0;
2957 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
2958 ASSERT(exceptionCode == 0);
2961 //------------------------------------------------------------------------------------------
2962 // RemoveNodePreservingChildrenCommand
2964 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
2965 : CompositeEditCommand(document), m_node(node)
2971 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
2977 void RemoveNodePreservingChildrenCommand::doApply()
2979 while (NodeImpl* curr = node()->firstChild()) {
2981 insertNodeBefore(curr, node());
2986 //------------------------------------------------------------------------------------------
2987 // ReplaceSelectionCommand
2989 ReplacementFragment::ReplacementFragment(DocumentFragmentImpl *fragment)
2990 : m_fragment(fragment), m_hasInterchangeNewlineComment(false), m_hasMoreThanOneBlock(false)
2993 m_type = EmptyFragment;
2999 NodeImpl *firstChild = m_fragment->firstChild();
3000 NodeImpl *lastChild = m_fragment->lastChild();
3003 m_type = EmptyFragment;
3007 if (firstChild == lastChild && firstChild->isTextNode()) {
3008 m_type = SingleTextNodeFragment;
3012 m_type = TreeFragment;
3014 NodeImpl *node = firstChild;
3015 int realBlockCount = 0;
3016 NodeImpl *commentToDelete = 0;
3018 NodeImpl *next = node->traverseNextNode();
3019 if (isInterchangeNewlineComment(node)) {
3020 m_hasInterchangeNewlineComment = true;
3021 commentToDelete = node;
3023 else if (isInterchangeConvertedSpaceSpan(node)) {
3025 while ((n = node->firstChild())) {
3028 insertNodeBefore(n, node);
3033 next = n->traverseNextNode();
3035 else if (isProbablyBlock(node))
3040 if (commentToDelete)
3041 removeNode(commentToDelete);
3043 int blockCount = realBlockCount;
3044 firstChild = m_fragment->firstChild();
3045 lastChild = m_fragment->lastChild();
3046 if (!isProbablyBlock(firstChild))
3048 if (!isProbablyBlock(lastChild) && realBlockCount > 0)
3052 m_hasMoreThanOneBlock = true;
3055 ReplacementFragment::~ReplacementFragment()
3058 m_fragment->deref();
3061 NodeImpl *ReplacementFragment::firstChild() const
3063 return m_fragment->firstChild();
3066 NodeImpl *ReplacementFragment::lastChild() const
3068 return m_fragment->lastChild();
3071 NodeImpl *ReplacementFragment::mergeStartNode() const
3073 NodeImpl *node = m_fragment->firstChild();
3075 NodeImpl *next = node->traverseNextNode();
3076 if (!isProbablyBlock(node))
3083 NodeImpl *ReplacementFragment::mergeEndNode() const
3085 NodeImpl *node = m_fragment->lastChild();
3086 while (node && node->lastChild())
3087 node = node->lastChild();
3089 NodeImpl *prev = node->traversePreviousNode();
3090 if (!isProbablyBlock(node)) {
3091 NodeImpl *previousSibling = node->previousSibling();
3093 if (!previousSibling || isProbablyBlock(previousSibling))
3095 node = previousSibling;
3096 previousSibling = node->previousSibling();
3104 void ReplacementFragment::pruneEmptyNodes()
3109 NodeImpl *node = m_fragment->firstChild();
3111 if ((node->isTextNode() && static_cast<TextImpl *>(node)->length() == 0) ||
3112 (isProbablyBlock(node) && node->childNodeCount() == 0)) {
3113 NodeImpl *next = node->traverseNextSibling();
3119 node = node->traverseNextNode();
3125 bool ReplacementFragment::isInterchangeNewlineComment(const NodeImpl *node)
3127 return isComment(node) && node->nodeValue() == KHTMLInterchangeNewline;
3130 bool ReplacementFragment::isInterchangeConvertedSpaceSpan(const NodeImpl *node)
3132 static DOMString convertedSpaceSpanClass(AppleConvertedSpace);
3133 return node->isHTMLElement() && static_cast<const HTMLElementImpl *>(node)->getAttribute(ATTR_CLASS) == convertedSpaceSpanClass;
3136 void ReplacementFragment::removeNode(NodeImpl *node)
3141 NodeImpl *parent = node->parentNode();
3145 int exceptionCode = 0;
3146 parent->removeChild(node, exceptionCode);
3147 ASSERT(exceptionCode == 0);
3150 void ReplacementFragment::insertNodeBefore(NodeImpl *node, NodeImpl *refNode)
3152 if (!node || !refNode)
3155 NodeImpl *parent = refNode->parentNode();
3159 int exceptionCode = 0;
3160 parent->insertBefore(node, refNode, exceptionCode);
3161 ASSERT(exceptionCode == 0);
3165 bool isComment(const NodeImpl *node)
3167 return node && node->nodeType() == Node::COMMENT_NODE;
3170 bool isProbablyBlock(const NodeImpl *node)
3175 switch (node->id()) {
3201 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
3202 : CompositeEditCommand(document),
3203 m_fragment(fragment),
3204 m_selectReplacement(selectReplacement),
3205 m_smartReplace(smartReplace)
3209 ReplaceSelectionCommand::~ReplaceSelectionCommand()
3213 void ReplaceSelectionCommand::doApply()
3215 Selection selection = endingSelection();
3216 VisiblePosition visibleStart(selection.start());
3217 VisiblePosition visibleEnd(selection.end());
3218 bool startAtStartOfLine = isFirstVisiblePositionOnLine(visibleStart);
3219 bool startAtStartOfBlock = isFirstVisiblePositionInBlock(visibleStart);
3220 bool startAtEndOfBlock = isLastVisiblePositionInBlock(visibleStart);
3221 bool startAtBlockBoundary = startAtStartOfBlock || startAtEndOfBlock;
3222 NodeImpl *startBlock = selection.start().node()->enclosingBlockFlowElement();
3223 NodeImpl *endBlock = selection.end().node()->enclosingBlockFlowElement();
3225 bool mergeStart = !(startAtStartOfLine && (m_fragment.hasInterchangeNewlineComment() || m_fragment.hasMoreThanOneBlock()));
3226 bool mergeEnd = !m_fragment.hasInterchangeNewlineComment() && m_fragment.hasMoreThanOneBlock();
3227 Position startPos = Position(selection.start().node()->enclosingBlockFlowElement(), 0);
3229 EStayInBlock upstreamStayInBlock = StayInBlock;
3231 // Delete the current selection, or collapse whitespace, as needed
3232 if (selection.isRange()) {
3233 deleteSelection(false, !(m_fragment.hasInterchangeNewlineComment() || m_fragment.hasMoreThanOneBlock()));
3235 else if (selection.isCaret() && mergeEnd && !startAtBlockBoundary) {
3236 // The start and the end need to wind up in separate blocks.
3237 // Insert a paragraph separator to make that happen.
3238 insertParagraphSeparator();
3239 upstreamStayInBlock = DoNotStayInBlock;
3242 selection = endingSelection();
3243 if (startAtStartOfBlock && startBlock->inDocument())
3244 startPos = Position(startBlock, 0);
3245 else if (startAtEndOfBlock)
3246 startPos = selection.start().downstream(StayInBlock);
3248 startPos = selection.start().upstream(upstreamStayInBlock);
3249 endPos = selection.end().downstream();
3251 // This command does not use any typing style that is set as a residual effect of
3253 // FIXME: Improve typing style.
3254 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3255 KHTMLPart *part = document()->part();
3256 part->clearTypingStyle();
3259 if (!m_fragment.firstChild())
3262 // Now that we are about to add content, check to see if a placeholder element
3264 NodeImpl *block = startPos.node()->enclosingBlockFlowElement();
3265 if (removeBlockPlaceholderIfNeeded(block)) {
3266 startPos = Position(block, 0);
3269 bool addLeadingSpace = false;
3270 bool addTrailingSpace = false;
3271 if (m_smartReplace) {
3272 addLeadingSpace = startPos.leadingWhitespacePosition().isNull();
3273 if (addLeadingSpace) {
3274 QChar previousChar = VisiblePosition(startPos).previous().character();
3275 if (!previousChar.isNull()) {
3276 addLeadingSpace = !part->isCharacterSmartReplaceExempt(previousChar, true);
3279 addTrailingSpace = endPos.trailingWhitespacePosition().isNull();
3280 if (addTrailingSpace) {
3281 QChar thisChar = VisiblePosition(endPos).character();
3282 if (!thisChar.isNull()) {
3283 addTrailingSpace = !part->isCharacterSmartReplaceExempt(thisChar, false);
3288 document()->updateLayout();
3290 NodeImpl *refBlock = startPos.node()->enclosingBlockFlowElement();
3291 Position insertionPos = startPos;
3292 bool insertBlocksBefore = true;
3294 NodeImpl *firstNodeInserted = 0;
3295 NodeImpl *lastNodeInserted = 0;
3296 bool lastNodeInsertedInMergeEnd = false;
3298 // prune empty nodes from fragment
3299 m_fragment.pruneEmptyNodes();
3301 // Merge content into the end block, if necessary.
3303 NodeImpl *node = m_fragment.mergeEndNode();
3305 NodeImpl *refNode = node;
3306 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3307 insertNodeAt(refNode, endPos.node(), endPos.offset());
3308 firstNodeInserted = refNode;
3309 lastNodeInserted = refNode;
3310 while (node && !isProbablyBlock(node)) {
3311 NodeImpl *next = node->nextSibling();
3312 insertNodeAfter(node, refNode);
3313 lastNodeInserted = node;
3317 lastNodeInsertedInMergeEnd = true;
3321 // prune empty nodes from fragment
3322 m_fragment.pruneEmptyNodes();
3324 // Merge content into the start block, if necessary.
3326 NodeImpl *node = m_fragment.mergeStartNode();
3327 NodeImpl *insertionNode = 0;
3329 NodeImpl *refNode = node;
3330 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3331 insertNodeAt(refNode, startPos.node(), startPos.offset());
3332 firstNodeInserted = refNode;
3333 if (!lastNodeInsertedInMergeEnd)
3334 lastNodeInserted = refNode;
3335 insertionNode = refNode;
3336 while (node && !isProbablyBlock(node)) {
3337 NodeImpl *next = node->nextSibling();
3338 insertNodeAfter(node, refNode);
3339 if (!lastNodeInsertedInMergeEnd)
3340 lastNodeInserted = node;
3341 insertionNode = node;
3347 insertionPos = Position(insertionNode, insertionNode->caretMaxOffset());
3348 insertBlocksBefore = false;
3351 // prune empty nodes from fragment
3352 m_fragment.pruneEmptyNodes();
3354 // Merge everything remaining.
3355 NodeImpl *node = m_fragment.firstChild();
3357 NodeImpl *refNode = node;
3358 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3359 if (isProbablyBlock(refNode) && (insertBlocksBefore || startAtStartOfBlock)) {
3360 insertNodeBefore(refNode, refBlock);
3362 else if (isProbablyBlock(refNode) && startAtEndOfBlock) {
3363 insertNodeAfter(refNode, refBlock);
3366 insertNodeAt(refNode, insertionPos.node(), insertionPos.offset());
3368 if (!firstNodeInserted)
3369 firstNodeInserted = refNode;
3370 if (!lastNodeInsertedInMergeEnd)
3371 lastNodeInserted = refNode;
3373 NodeImpl *next = node->nextSibling();
3374 insertNodeAfter(node, refNode);
3375 if (!lastNodeInsertedInMergeEnd)
3376 lastNodeInserted = node;
3380 document()->updateLayout();
3381 insertionPos = Position(lastNodeInserted, lastNodeInserted->caretMaxOffset());
3384 // Handle "smart replace" whitespace
3385 if (addTrailingSpace && lastNodeInserted) {
3386 if (lastNodeInserted->isTextNode()) {
3387 TextImpl *text = static_cast<TextImpl *>(lastNodeInserted);
3388 insertTextIntoNode(text, text->length(), nonBreakingSpaceString());
3389 insertionPos = Position(text, text->length());
3392 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3393 insertNodeAfter(node, lastNodeInserted);
3394 if (!firstNodeInserted)
3395 firstNodeInserted = node;
3396 lastNodeInserted = node;
3397 insertionPos = Position(node, 1);
3401 if (addLeadingSpace && firstNodeInserted) {
3402 if (firstNodeInserted->isTextNode()) {
3403 TextImpl *text = static_cast<TextImpl *>(firstNodeInserted);
3404 insertTextIntoNode(text, 0, nonBreakingSpaceString());
3407 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3408 insertNodeBefore(node, firstNodeInserted);
3409 firstNodeInserted = node;
3410 if (!lastNodeInsertedInMergeEnd)
3411 lastNodeInserted = node;
3415 // Handle trailing newline
3416 if (m_fragment.hasInterchangeNewlineComment()) {
3417 if (startBlock == endBlock && !isProbablyBlock(lastNodeInserted)) {
3418 setEndingSelection(insertionPos);
3419 insertParagraphSeparator();
3420 endPos = endingSelection().end().downstream();
3422 completeHTMLReplacement(startPos, endPos);
3425 if (lastNodeInserted->id() == ID_BR && !document()->inStrictMode()) {
3426 document()->updateLayout();
3427 VisiblePosition pos(Position(lastNodeInserted, 0));
3428 if (isLastVisiblePositionInBlock(pos)) {
3429 NodeImpl *next = lastNodeInserted->traverseNextNode();
3430 bool hasTrailingBR = next && next->id() == ID_BR && lastNodeInserted->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
3431 if (!hasTrailingBR) {
3432 // Insert an "extra" BR at the end of the block.
3433 int exceptionCode = 0;
3434 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
3435 ASSERT(exceptionCode == 0);
3436 insertNodeBefore(extraBreakNode, lastNodeInserted);
3440 completeHTMLReplacement(firstNodeInserted, lastNodeInserted);
3444 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &start, const Position &end)
3446 if (start.isNull() || !start.node()->inDocument() || end.isNull() || !end.node()->inDocument())
3448 m_selectReplacement ? setEndingSelection(Selection(start, end)) : setEndingSelection(end);
3449 rebalanceWhitespace();
3452 void ReplaceSelectionCommand::completeHTMLReplacement(NodeImpl *firstNodeInserted, NodeImpl *lastNodeInserted)
3454 if (!firstNodeInserted || !firstNodeInserted->inDocument() ||
3455 !lastNodeInserted || !lastNodeInserted->inDocument())
3458 // Find the last leaf.
3459 NodeImpl *lastLeaf = lastNodeInserted;
3461 NodeImpl *nextChild = lastLeaf->lastChild();
3464 lastLeaf = nextChild;
3467 // Find the first leaf.
3468 NodeImpl *firstLeaf = firstNodeInserted;
3470 NodeImpl *nextChild = firstLeaf->firstChild();
3473 firstLeaf = nextChild;
3476 Position start(firstLeaf, firstLeaf->caretMinOffset());
3477 Position end(lastLeaf, lastLeaf->caretMaxOffset());
3478 Selection replacementSelection(start, end);
3479 if (m_selectReplacement) {
3480 // Select what was inserted.
3481 setEndingSelection(replacementSelection);
3484 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
3485 setEndingSelection(end);
3487 rebalanceWhitespace();
3490 //------------------------------------------------------------------------------------------
3491 // SetNodeAttributeCommand
3493 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
3494 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
3498 ASSERT(!m_value.isNull());
3501 SetNodeAttributeCommand::~SetNodeAttributeCommand()
3507 void SetNodeAttributeCommand::doApply()
3510 ASSERT(!m_value.isNull());
3512 int exceptionCode = 0;
3513 m_oldValue = m_element->getAttribute(m_attribute);
3514 m_element->setAttribute(m_attribute, m_value.implementation(), exceptionCode);
3515 ASSERT(exceptionCode == 0);
3518 void SetNodeAttributeCommand::doUnapply()
3521 ASSERT(!m_oldValue.isNull());
3523 int exceptionCode = 0;
3524 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
3525 ASSERT(exceptionCode == 0);
3528 //------------------------------------------------------------------------------------------
3529 // SplitTextNodeCommand
3531 SplitTextNodeCommand::SplitTextNodeCommand(DocumentImpl *document, TextImpl *text, long offset)
3532 : EditCommand(document), m_text1(0), m_text2(text), m_offset(offset)
3535 ASSERT(m_text2->length() > 0);
3540 SplitTextNodeCommand::~SplitTextNodeCommand()
3549 void SplitTextNodeCommand::doApply()
3552 ASSERT(m_offset > 0);
3554 int exceptionCode = 0;
3556 // EDIT FIXME: This should use better smarts for figuring out which portion
3557 // of the split to copy (based on their comparitive sizes). We should also
3558 // just use the DOM's splitText function.
3561 // create only if needed.
3562 // if reapplying, this object will already exist.
3563 m_text1 = document()->createTextNode(m_text2->substringData(0, m_offset, exceptionCode));
3564 ASSERT(exceptionCode == 0);
3569 m_text2->deleteData(0, m_offset, exceptionCode);
3570 ASSERT(exceptionCode == 0);
3572 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
3573 ASSERT(exceptionCode == 0);
3575 ASSERT(m_text2->previousSibling()->isTextNode());
3576 ASSERT(m_text2->previousSibling() == m_text1);
3579 void SplitTextNodeCommand::doUnapply()
3584 ASSERT(m_text1->nextSibling() == m_text2);
3586 int exceptionCode = 0;
3587 m_text2->insertData(0, m_text1->data(), exceptionCode);
3588 ASSERT(exceptionCode == 0);
3590 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
3591 ASSERT(exceptionCode == 0);
3593 m_offset = m_text1->length();
3596 //------------------------------------------------------------------------------------------
3599 TypingCommand::TypingCommand(DocumentImpl *document, ETypingCommand commandType, const DOMString &textToInsert, bool selectInsertedText)
3600 : CompositeEditCommand(document), m_commandType(commandType), m_textToInsert(textToInsert), m_openForMoreTyping(true), m_applyEditing(false), m_selectInsertedText(selectInsertedText)
3604 void TypingCommand::deleteKeyPressed(DocumentImpl *document)
3608 KHTMLPart *part = document->part();
3611 EditCommandPtr lastEditCommand = part->lastEditCommand();
3612 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3613 static_cast<TypingCommand *>(lastEditCommand.get())->deleteKeyPressed();
3616 EditCommandPtr cmd(new TypingCommand(document, DeleteKey));
3621 void TypingCommand::insertText(DocumentImpl *document, const DOMString &text, bool selectInsertedText)
3625 KHTMLPart *part = document->part();
3628 EditCommandPtr lastEditCommand = part->lastEditCommand();
3629 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3630 static_cast<TypingCommand *>(lastEditCommand.get())->insertText(text, selectInsertedText);
3633 EditCommandPtr cmd(new TypingCommand(document, InsertText, text, selectInsertedText));
3638 void TypingCommand::insertLineBreak(DocumentImpl *document)
3642 KHTMLPart *part = document->part();
3645 EditCommandPtr lastEditCommand = part->lastEditCommand();
3646 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3647 static_cast<TypingCommand *>(lastEditCommand.get())->insertLineBreak();
3650 EditCommandPtr cmd(new TypingCommand(document, InsertLineBreak));
3655 void TypingCommand::insertParagraphSeparatorInQuotedContent(DocumentImpl *document)
3659 KHTMLPart *part = document->part();
3662 EditCommandPtr lastEditCommand = part->lastEditCommand();
3663 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3664 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparatorInQuotedContent();
3667 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparatorInQuotedContent));
3672 void TypingCommand::insertParagraphSeparator(DocumentImpl *document)
3676 KHTMLPart *part = document->part();
3679 EditCommandPtr lastEditCommand = part->lastEditCommand();
3680 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3681 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparator();
3684 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparator));
3689 bool TypingCommand::isOpenForMoreTypingCommand(const EditCommandPtr &cmd)
3691 return cmd.isTypingCommand() &&
3692 static_cast<const TypingCommand *>(cmd.get())->openForMoreTyping();
3695 void TypingCommand::closeTyping(const EditCommandPtr &cmd)
3697 if (isOpenForMoreTypingCommand(cmd))
3698 static_cast<TypingCommand *>(cmd.get())->closeTyping();
3701 void TypingCommand::doApply()
3703 if (endingSelection().isNone())
3706 switch (m_commandType) {
3710 case InsertLineBreak:
3713 case InsertParagraphSeparator:
3714 insertParagraphSeparator();
3716 case InsertParagraphSeparatorInQuotedContent:
3717 insertParagraphSeparatorInQuotedContent();
3720 insertText(m_textToInsert, m_selectInsertedText);
3724 ASSERT_NOT_REACHED();
3727 void TypingCommand::markMisspellingsAfterTyping()
3729 // Take a look at the selection that results after typing and determine whether we need to spellcheck.
3730 // Since the word containing the current selection is never marked, this does a check to
3731 // see if typing made a new word that is not in the current selection. Basically, you
3732 // get this by being at the end of a word and typing a space.
3733 VisiblePosition start(endingSelection().start());
3734 VisiblePosition previous = start.previous();
3735 if (previous.isNotNull()) {
3736 VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
3737 VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
3739 KWQ(document()->part())->markMisspellingsInAdjacentWords(p1);
3743 void TypingCommand::typingAddedToOpenCommand()
3745 markMisspellingsAfterTyping();
3746 // Do not apply editing to the part on the first time through.
3747 // The part will get told in the same way as all other commands.
3748 // But since this command stays open and is used for additional typing,
3749 // we need to tell the part here as other commands are added.
3750 if (m_applyEditing) {
3751 EditCommandPtr cmd(this);
3752 document()->part()->appliedEditing(cmd);
3754 m_applyEditing = true;
3757 void TypingCommand::insertText(const DOMString &text, bool selectInsertedText)
3759 // FIXME: Improve typing style.
3760 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3761 if (document()->part()->typingStyle() || m_cmds.count() == 0) {
3762 InsertTextCommand *impl = new InsertTextCommand(document());
3763 EditCommandPtr cmd(impl);
3764 applyCommandToComposite(cmd);
3765 impl->input(text, selectInsertedText);
3768 EditCommandPtr lastCommand = m_cmds.last();
3769 if (lastCommand.isInsertTextCommand()) {
3770 InsertTextCommand *impl = static_cast<InsertTextCommand *>(lastCommand.get());
3771 impl->input(text, selectInsertedText);
3774 InsertTextCommand *impl = new InsertTextCommand(document());
3775 EditCommandPtr cmd(impl);
3776 applyCommandToComposite(cmd);
3777 impl->input(text, selectInsertedText);
3780 typingAddedToOpenCommand();
3783 void TypingCommand::insertLineBreak()
3785 EditCommandPtr cmd(new InsertLineBreakCommand(document()));
3786 applyCommandToComposite(cmd);
3787 typingAddedToOpenCommand();
3790 void TypingCommand::insertParagraphSeparator()
3792 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
3793 applyCommandToComposite(cmd);
3794 typingAddedToOpenCommand();
3797 void TypingCommand::insertParagraphSeparatorInQuotedContent()
3799 EditCommandPtr cmd(new InsertParagraphSeparatorInQuotedContentCommand(document()));
3800 applyCommandToComposite(cmd);
3801 typingAddedToOpenCommand();
3804 void TypingCommand::issueCommandForDeleteKey()
3806 Selection selectionToDelete;
3808 switch (endingSelection().state()) {
3809 case Selection::RANGE:
3810 selectionToDelete = endingSelection();
3812 case Selection::CARET: {
3813 // Handle delete at beginning-of-block case.
3814 // Do nothing in the case that the caret is at the start of a
3815 // root editable element or at the start of a document.
3816 Position pos(endingSelection().start());
3817 Position start = VisiblePosition(pos).previous().deepEquivalent();
3818 Position end = VisiblePosition(pos).deepEquivalent();
3819 if (start.isNotNull() && end.isNotNull() && start.node()->rootEditableElement() == end.node()->rootEditableElement())
3820 selectionToDelete = Selection(start, end);
3823 case Selection::NONE:
3824 ASSERT_NOT_REACHED();
3828 if (selectionToDelete.isCaretOrRange()) {
3829 deleteSelection(selectionToDelete);
3830 typingAddedToOpenCommand();
3834 void TypingCommand::deleteKeyPressed()
3836 // EDIT FIXME: The ifdef'ed out code below should be re-enabled.
3837 // In order for this to happen, the deleteCharacter case
3838 // needs work. Specifically, the caret-positioning code
3839 // and whitespace-handling code in DeleteSelectionCommand::doApply()
3840 // needs to be factored out so it can be used again here.
3841 // Until that work is done, issueCommandForDeleteKey() does the
3842 // right thing, but less efficiently and with the cost of more
3844 issueCommandForDeleteKey();
3846 if (m_cmds.count() == 0) {
3847 issueCommandForDeleteKey();
3850 EditCommandPtr lastCommand = m_cmds.last();
3851 if (lastCommand.isInsertTextCommand()) {
3852 InsertTextCommand &cmd = static_cast<InsertTextCommand &>(lastCommand);
3853 cmd.deleteCharacter();
3854 if (cmd.charactersAdded() == 0) {
3855 removeCommand(lastCommand);
3858 else if (lastCommand.isInsertLineBreakCommand()) {
3859 lastCommand.unapply();
3860 removeCommand(lastCommand);
3863 issueCommandForDeleteKey();
3869 void TypingCommand::removeCommand(const EditCommandPtr &cmd)
3871 // NOTE: If the passed-in command is the last command in the
3872 // composite, we could remove all traces of this typing command
3873 // from the system, including the undo chain. Other editors do
3874 // not do this, but we could.
3877 if (m_cmds.count() == 0)
3878 setEndingSelection(startingSelection());
3880 setEndingSelection(m_cmds.last().endingSelection());
3883 bool TypingCommand::preservesTypingStyle() const
3885 switch (m_commandType) {
3888 case InsertLineBreak:
3889 case InsertParagraphSeparator:
3890 case InsertParagraphSeparatorInQuotedContent:
3894 ASSERT_NOT_REACHED();
3898 bool TypingCommand::isTypingCommand() const
3903 } // namespace khtml