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, pos.node()->nodeName().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, node->nodeName().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 EditAction EditCommandPtr::editingAction() const
271 IF_IMPL_NULL_RETURN_ARG(EditActionUnspecified);
272 return get()->editingAction();
275 DocumentImpl * const EditCommandPtr::document() const
277 IF_IMPL_NULL_RETURN_ARG(0);
278 return get()->document();
281 Selection EditCommandPtr::startingSelection() const
283 IF_IMPL_NULL_RETURN_ARG(Selection());
284 return get()->startingSelection();
287 Selection EditCommandPtr::endingSelection() const
289 IF_IMPL_NULL_RETURN_ARG(Selection());
290 return get()->endingSelection();
293 void EditCommandPtr::setStartingSelection(const Selection &s) const
296 get()->setStartingSelection(s);
299 void EditCommandPtr::setEndingSelection(const Selection &s) const
302 get()->setEndingSelection(s);
305 CSSMutableStyleDeclarationImpl *EditCommandPtr::typingStyle() const
307 IF_IMPL_NULL_RETURN_ARG(0);
308 return get()->typingStyle();
311 void EditCommandPtr::setTypingStyle(CSSMutableStyleDeclarationImpl *style) const
314 get()->setTypingStyle(style);
317 EditCommandPtr EditCommandPtr::parent() const
319 IF_IMPL_NULL_RETURN_ARG(0);
320 return get()->parent();
323 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
326 get()->setParent(cmd.get());
329 EditCommandPtr &EditCommandPtr::emptyCommand()
331 static EditCommandPtr m_emptyCommand;
332 return m_emptyCommand;
335 //------------------------------------------------------------------------------------------
338 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, ELegacyHTMLStyles usesLegacyStyles)
339 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
341 init(style, Position());
344 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
345 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
347 init(style, position);
350 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
353 CSSMutableStyleDeclarationImpl *mutableStyle = style->makeMutable();
357 QString styleText("");
359 QValueListConstIterator<CSSProperty> end;
360 for (QValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
361 const CSSProperty *property = &*it;
363 // If position is empty or the position passed in already has the
364 // style, just move on.
365 if (position.isNotNull() && currentlyHasStyle(position, property))
368 // If needed, figure out if this change is a legacy HTML style change.
369 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
373 styleText += property->cssText().string();
376 mutableStyle->deref();
378 // Save the result for later
379 m_cssStyle = styleText.stripWhiteSpace();
382 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
384 DOMString valueText(property->value()->cssText());
385 switch (property->id()) {
386 case CSS_PROP_FONT_WEIGHT:
387 if (strcasecmp(valueText, "bold") == 0) {
392 case CSS_PROP_FONT_STYLE:
393 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
394 m_applyItalic = true;
402 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
404 ASSERT(pos.isNotNull());
405 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
408 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
413 bool result = strcasecmp(value->cssText(), property->value()->cssText()) == 0;
418 //------------------------------------------------------------------------------------------
421 EditCommand::EditCommand(DocumentImpl *document)
422 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
425 ASSERT(m_document->part());
427 m_startingSelection = m_document->part()->selection();
428 m_endingSelection = m_startingSelection;
430 m_document->part()->setSelection(Selection(), false, true);
433 EditCommand::~EditCommand()
438 m_typingStyle->deref();
441 void EditCommand::apply()
444 ASSERT(m_document->part());
445 ASSERT(state() == NotApplied);
447 KHTMLPart *part = m_document->part();
449 ASSERT(part->selection().isNone());
455 // FIXME: Improve typing style.
456 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
457 if (!preservesTypingStyle())
460 if (!isCompositeStep()) {
461 document()->updateLayout();
462 EditCommandPtr cmd(this);
463 part->appliedEditing(cmd);
467 void EditCommand::unapply()
470 ASSERT(m_document->part());
471 ASSERT(state() == Applied);
473 bool topLevel = !isCompositeStep();
475 KHTMLPart *part = m_document->part();
478 part->setSelection(Selection(), false, true);
480 ASSERT(part->selection().isNone());
484 m_state = NotApplied;
487 document()->updateLayout();
488 EditCommandPtr cmd(this);
489 part->unappliedEditing(cmd);
493 void EditCommand::reapply()
496 ASSERT(m_document->part());
497 ASSERT(state() == NotApplied);
499 bool topLevel = !isCompositeStep();
501 KHTMLPart *part = m_document->part();
504 part->setSelection(Selection(), false, true);
506 ASSERT(part->selection().isNone());
513 document()->updateLayout();
514 EditCommandPtr cmd(this);
515 part->reappliedEditing(cmd);
519 void EditCommand::doReapply()
524 EditAction EditCommand::editingAction() const
526 return EditActionUnspecified;
529 void EditCommand::setStartingSelection(const Selection &s)
531 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
532 cmd->m_startingSelection = s;
535 void EditCommand::setEndingSelection(const Selection &s)
537 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
538 cmd->m_endingSelection = s;
541 void EditCommand::assignTypingStyle(CSSMutableStyleDeclarationImpl *style)
543 if (m_typingStyle == style)
546 CSSMutableStyleDeclarationImpl *old = m_typingStyle;
547 m_typingStyle = style;
549 m_typingStyle->ref();
554 void EditCommand::setTypingStyle(CSSMutableStyleDeclarationImpl *style)
556 // FIXME: Improve typing style.
557 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
558 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
559 cmd->assignTypingStyle(style);
562 bool EditCommand::preservesTypingStyle() const
567 bool EditCommand::isInsertTextCommand() const
572 bool EditCommand::isTypingCommand() const
577 //------------------------------------------------------------------------------------------
578 // CompositeEditCommand
580 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
581 : EditCommand(document)
585 void CompositeEditCommand::doUnapply()
587 if (m_cmds.count() == 0) {
591 for (int i = m_cmds.count() - 1; i >= 0; --i)
592 m_cmds[i]->unapply();
594 setState(NotApplied);
597 void CompositeEditCommand::doReapply()
599 if (m_cmds.count() == 0) {
603 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
610 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
612 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
614 cmd.setStartingSelection(endingSelection());
615 cmd.setEndingSelection(endingSelection());
621 void CompositeEditCommand::insertParagraphSeparator()
623 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
624 applyCommandToComposite(cmd);
627 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
629 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
630 applyCommandToComposite(cmd);
633 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
635 if (refChild->parentNode()->lastChild() == refChild) {
636 appendNode(insertChild, refChild->parentNode());
639 ASSERT(refChild->nextSibling());
640 insertNodeBefore(insertChild, refChild->nextSibling());
644 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
646 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
647 NodeImpl *child = refChild->firstChild();
648 for (long i = 0; child && i < offset; i++)
649 child = child->nextSibling();
651 insertNodeBefore(insertChild, child);
653 appendNode(insertChild, refChild);
655 else if (refChild->caretMinOffset() >= offset) {
656 insertNodeBefore(insertChild, refChild);
658 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
659 splitTextNode(static_cast<TextImpl *>(refChild), offset);
660 insertNodeBefore(insertChild, refChild);
663 insertNodeAfter(insertChild, refChild);
667 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
669 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
670 applyCommandToComposite(cmd);
673 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
675 if (isTableStructureNode(node)) {
676 // Do not remove an element of table structure; remove its contents.
677 NodeImpl *child = node->firstChild();
679 NodeImpl *remove = child;
680 child = child->nextSibling();
681 removeFullySelectedNode(remove);
685 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
686 applyCommandToComposite(cmd);
690 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
692 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
693 applyCommandToComposite(cmd);
696 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
698 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
699 applyCommandToComposite(cmd);
702 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
704 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
705 applyCommandToComposite(cmd);
708 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
710 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
711 applyCommandToComposite(cmd);
714 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
716 InsertTextCommand *impl = new InsertTextCommand(document());
717 EditCommandPtr cmd(impl);
718 applyCommandToComposite(cmd);
719 impl->input(text, selectInsertedText);
722 void CompositeEditCommand::insertTextIntoNode(TextImpl *node, long offset, const DOMString &text)
724 EditCommandPtr cmd(new InsertIntoTextNode(document(), node, offset, text));
725 applyCommandToComposite(cmd);
728 void CompositeEditCommand::deleteTextFromNode(TextImpl *node, long offset, long count)
730 EditCommandPtr cmd(new DeleteFromTextNodeCommand(document(), node, offset, count));
731 applyCommandToComposite(cmd);
734 void CompositeEditCommand::replaceTextInNode(TextImpl *node, long offset, long count, const DOMString &replacementText)
736 EditCommandPtr deleteCommand(new DeleteFromTextNodeCommand(document(), node, offset, count));
737 applyCommandToComposite(deleteCommand);
738 EditCommandPtr insertCommand(new InsertIntoTextNode(document(), node, offset, replacementText));
739 applyCommandToComposite(insertCommand);
742 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
744 if (endingSelection().isRange()) {
745 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
746 applyCommandToComposite(cmd);
750 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
752 if (selection.isRange()) {
753 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
754 applyCommandToComposite(cmd);
758 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
760 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
761 applyCommandToComposite(cmd);
764 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
766 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
767 applyCommandToComposite(cmd);
770 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
772 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
773 applyCommandToComposite(cmd);
776 void CompositeEditCommand::rebalanceWhitespace()
778 Selection selection = endingSelection();
779 if (selection.isCaretOrRange()) {
780 EditCommandPtr startCmd(new RebalanceWhitespaceCommand(document(), endingSelection().start()));
781 applyCommandToComposite(startCmd);
782 if (selection.isRange()) {
783 EditCommandPtr endCmd(new RebalanceWhitespaceCommand(document(), endingSelection().end()));
784 applyCommandToComposite(endCmd);
789 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
791 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
792 // and ApplyStyleCommand::computeStyleChange.
793 // Both function do similar work, and the common parts could be factored out.
795 // FIXME: Improve typing style.
796 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
798 // update document layout once before running the rest of the function
799 // so that we avoid the expense of updating before each and every call
800 // to check a computed style
801 document()->updateLayout();
803 StyleChange styleChange(document()->part()->typingStyle());
805 NodeImpl *childToAppend = child;
806 int exceptionCode = 0;
808 if (styleChange.applyItalic()) {
809 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
810 ASSERT(exceptionCode == 0);
811 italicElement->appendChild(childToAppend, exceptionCode);
812 ASSERT(exceptionCode == 0);
813 childToAppend = italicElement;
816 if (styleChange.applyBold()) {
817 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
818 ASSERT(exceptionCode == 0);
819 boldElement->appendChild(childToAppend, exceptionCode);
820 ASSERT(exceptionCode == 0);
821 childToAppend = boldElement;
824 if (styleChange.cssStyle().length() > 0) {
825 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
826 ASSERT(exceptionCode == 0);
827 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
828 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
829 styleElement->appendChild(childToAppend, exceptionCode);
830 ASSERT(exceptionCode == 0);
831 childToAppend = styleElement;
834 return childToAppend;
837 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
839 if (!textNode || !textNode->renderer() || start >= end)
842 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
843 InlineTextBox *box = textRenderer->firstTextBox();
845 // whole text node is empty
846 removeNode(textNode);
850 long length = textNode->length();
851 if (start >= length || end > length)
855 InlineTextBox *prevBox = 0;
856 DOMStringImpl *str = 0;
858 // This loop structure works to process all gaps preceding a box,
859 // and also will look at the gap after the last box.
860 while (prevBox || box) {
861 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
863 // No more chance for any intersections
866 int gapEnd = box ? box->m_start : length;
867 bool indicesIntersect = start <= gapEnd && end >= gapStart;
868 int gapLen = gapEnd - gapStart;
869 if (indicesIntersect && gapLen > 0) {
870 gapStart = kMax(gapStart, start);
871 gapEnd = kMin(gapEnd, end);
873 str = textNode->string()->substring(start, end - start);
876 // remove text in the gap
877 str->remove(gapStart - start - removed, gapLen);
883 box = box->nextTextBox();
887 // Replace the text between start and end with our pruned version.
889 replaceTextInNode(textNode, start, end - start, str);
892 // Assert that we are not going to delete all of the text in the node.
893 // If we were, that should have been done above with the call to
894 // removeNode and return.
895 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
896 deleteTextFromNode(textNode, start, end - start);
902 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
904 if (start.isNull() || end.isNull())
907 if (RangeImpl::compareBoundaryPoints(start, end) >= 0)
910 NodeImpl *node = start.node();
912 NodeImpl *next = node->traverseNextNode();
914 if (node->isTextNode()) {
915 TextImpl *textNode = static_cast<TextImpl *>(node);
916 bool isStartNode = node == start.node();
917 bool isEndNode = node == end.node();
918 int startOffset = isStartNode ? start.offset() : 0;
919 int endOffset = isEndNode ? end.offset() : textNode->length();
920 deleteInsignificantText(textNode, startOffset, endOffset);
923 if (node == end.node())
929 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
931 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
932 deleteInsignificantText(pos, end);
935 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
940 document()->updateLayout();
942 RenderObject *renderer = node->renderer();
943 if (!renderer || !renderer->isBlockFlow())
946 if (renderer->height() > 0)
949 appendNode(createBlockPlaceholderElement(document()), node);
952 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
957 document()->updateLayout();
959 RenderObject *renderer = node->renderer();
960 if (!renderer || !renderer->isBlockFlow())
963 // This code will remove a block placeholder if it still is at the end
964 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
965 // Of course, a person who hand-edits an HTML file could move a
966 // placeholder around, but it seems OK to be unconcerned about that case.
967 NodeImpl *last = node->lastChild();
968 if (last && last->isHTMLElement()) {
969 ElementImpl *element = static_cast<ElementImpl *>(last);
970 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
978 //==========================================================================================
980 //------------------------------------------------------------------------------------------
983 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
984 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
986 ASSERT(m_appendChild);
987 m_appendChild->ref();
989 ASSERT(m_parentNode);
993 AppendNodeCommand::~AppendNodeCommand()
995 ASSERT(m_appendChild);
996 m_appendChild->deref();
998 ASSERT(m_parentNode);
999 m_parentNode->deref();
1002 void AppendNodeCommand::doApply()
1004 ASSERT(m_appendChild);
1005 ASSERT(m_parentNode);
1007 int exceptionCode = 0;
1008 m_parentNode->appendChild(m_appendChild, exceptionCode);
1009 ASSERT(exceptionCode == 0);
1012 void AppendNodeCommand::doUnapply()
1014 ASSERT(m_appendChild);
1015 ASSERT(m_parentNode);
1016 ASSERT(state() == Applied);
1018 int exceptionCode = 0;
1019 m_parentNode->removeChild(m_appendChild, exceptionCode);
1020 ASSERT(exceptionCode == 0);
1023 //------------------------------------------------------------------------------------------
1024 // ApplyStyleCommand
1026 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style, EditAction editingAction)
1027 : CompositeEditCommand(document), m_style(style->makeMutable()), m_editingAction(editingAction)
1033 ApplyStyleCommand::~ApplyStyleCommand()
1039 void ApplyStyleCommand::doApply()
1041 // apply the block-centric properties of the style
1042 CSSMutableStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
1044 applyBlockStyle(blockStyle);
1046 // apply any remaining styles to the inline elements
1047 // NOTE: hopefully, this string comparison is the same as checking for a non-null diff
1048 if (blockStyle->length() < m_style->length()) {
1049 CSSMutableStyleDeclarationImpl *inlineStyle = m_style->copy();
1051 blockStyle->diff(inlineStyle);
1052 applyInlineStyle(inlineStyle);
1053 inlineStyle->deref();
1056 blockStyle->deref();
1058 setEndingSelectionNeedsLayout();
1061 EditAction ApplyStyleCommand::editingAction() const
1063 return m_editingAction;
1066 void ApplyStyleCommand::applyBlockStyle(CSSMutableStyleDeclarationImpl *style)
1068 // update document layout once before removing styles
1069 // so that we avoid the expense of updating before each and every call
1070 // to check a computed style
1071 document()->updateLayout();
1073 // get positions we want to use for applying style
1074 Position start(endingSelection().start());
1075 Position end(endingSelection().end());
1077 // remove current values, if any, of the specified styles from the blocks
1078 // NOTE: tracks the previous block to avoid repeated processing
1079 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1080 NodeImpl *prevBlock = 0;
1081 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1082 NodeImpl *block = node->enclosingBlockFlowElement();
1083 if (block != prevBlock && block->isHTMLElement()) {
1084 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1089 // apply specified styles to the block flow elements in the selected range
1091 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1092 NodeImpl *block = node->enclosingBlockFlowElement();
1093 if (block != prevBlock && block->isHTMLElement()) {
1094 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1100 void ApplyStyleCommand::applyInlineStyle(CSSMutableStyleDeclarationImpl *style)
1102 // adjust to the positions we want to use for applying style
1103 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1104 Position end(endingSelection().end().upstream(StayInBlock));
1106 // update document layout once before removing styles
1107 // so that we avoid the expense of updating before each and every call
1108 // to check a computed style
1109 document()->updateLayout();
1111 // Remove style from the selection.
1112 // Use the upstream position of the start for removing style.
1113 // This will ensure we remove all traces of the relevant styles from the selection
1114 // and prevent us from adding redundant ones, as described in:
1115 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1116 removeInlineStyle(style, start.upstream(), end);
1118 // split the start node if the selection starts inside of it
1119 bool splitStart = splitTextAtStartIfNeeded(start, end);
1121 start = endingSelection().start();
1122 end = endingSelection().end();
1125 // split the end node if the selection ends inside of it
1126 splitTextAtEndIfNeeded(start, end);
1127 start = endingSelection().start();
1128 end = endingSelection().end();
1130 // update document layout once before running the rest of the function
1131 // so that we avoid the expense of updating before each and every call
1132 // to check a computed style
1133 document()->updateLayout();
1135 if (start.node() == end.node()) {
1136 // simple case...start and end are the same node
1137 addInlineStyleIfNeeded(style, start.node(), end.node());
1140 NodeImpl *node = start.node();
1142 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1143 NodeImpl *runStart = node;
1145 NodeImpl *next = node->traverseNextNode();
1146 // Break if node is the end node, or if the next node does not fit in with
1147 // the current group.
1148 if (node == end.node() ||
1149 runStart->parentNode() != next->parentNode() ||
1150 (next->isHTMLElement() && next->id() != ID_BR) ||
1151 (next->renderer() && !next->renderer()->isInline()))
1155 // Now apply style to the run we found.
1156 addInlineStyleIfNeeded(style, runStart, node);
1158 if (node == end.node())
1160 node = node->traverseNextNode();
1165 //------------------------------------------------------------------------------------------
1166 // ApplyStyleCommand: style-removal helpers
1168 bool ApplyStyleCommand::isHTMLStyleNode(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1170 QValueListConstIterator<CSSProperty> end;
1171 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1172 switch ((*it).id()) {
1173 case CSS_PROP_FONT_WEIGHT:
1174 if (elem->id() == ID_B)
1177 case CSS_PROP_FONT_STYLE:
1178 if (elem->id() == ID_I)
1187 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1189 // This node can be removed.
1190 // EDIT FIXME: This does not handle the case where the node
1191 // has attributes. But how often do people add attributes to <B> tags?
1192 // Not so often I think.
1194 removeNodePreservingChildren(elem);
1197 void ApplyStyleCommand::removeCSSStyle(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1202 CSSMutableStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1206 QValueListConstIterator<CSSProperty> end;
1207 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1208 int propertyID = (*it).id();
1209 CSSValueImpl *value = decl->getPropertyCSSValue(propertyID);
1212 removeCSSProperty(decl, propertyID);
1217 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1218 // Check to see if the span is one we added to apply style.
1219 // If it is, and there are no more attributes on the span other than our
1220 // class marker, remove the span.
1221 if (decl->length() == 0) {
1222 removeNodeAttribute(elem, ATTR_STYLE);
1223 NamedAttrMapImpl *map = elem->attributes();
1224 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1225 removeNodePreservingChildren(elem);
1230 void ApplyStyleCommand::removeBlockStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1232 ASSERT(start.isNotNull());
1233 ASSERT(end.isNotNull());
1234 ASSERT(start.node()->inDocument());
1235 ASSERT(end.node()->inDocument());
1236 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1240 void ApplyStyleCommand::removeInlineStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1242 ASSERT(start.isNotNull());
1243 ASSERT(end.isNotNull());
1244 ASSERT(start.node()->inDocument());
1245 ASSERT(end.node()->inDocument());
1246 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1248 NodeImpl *node = start.node();
1250 NodeImpl *next = node->traverseNextNode();
1251 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1252 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1253 if (isHTMLStyleNode(style, elem))
1254 removeHTMLStyleNode(elem);
1256 removeCSSStyle(style, elem);
1258 if (node == end.node())
1264 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1268 Position pos = Position(node, node->childNodeCount()).upstream();
1269 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1270 RangeImpl::compareBoundaryPoints(pos, end) <= 0;
1273 //------------------------------------------------------------------------------------------
1274 // ApplyStyleCommand: style-application helpers
1277 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1279 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1280 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1281 TextImpl *text = static_cast<TextImpl *>(start.node());
1282 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1283 applyCommandToComposite(cmd);
1284 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1290 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1292 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1293 TextImpl *text = static_cast<TextImpl *>(end.node());
1294 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1295 EditCommandPtr cmd(impl);
1296 applyCommandToComposite(cmd);
1297 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1299 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1300 return impl->node()->previousSibling();
1305 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1311 NodeImpl *node = startNode;
1313 NodeImpl *next = node->traverseNextNode();
1314 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1316 appendNode(node, element);
1318 if (node == endNode)
1324 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *block)
1326 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1328 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1329 if (styleChange.cssStyle().length() > 0) {
1330 DOMString cssText = styleChange.cssStyle();
1331 CSSMutableStyleDeclarationImpl *decl = block->inlineStyleDecl();
1333 cssText += decl->cssText();
1334 block->setAttribute(ATTR_STYLE, cssText);
1338 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1340 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1341 // Both functions do similar work, and the common parts could be factored out.
1343 StyleChange styleChange(style, Position(startNode, 0));
1344 int exceptionCode = 0;
1346 if (styleChange.cssStyle().length() > 0) {
1347 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1348 ASSERT(exceptionCode == 0);
1349 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1350 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1351 insertNodeBefore(styleElement, startNode);
1352 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1355 if (styleChange.applyBold()) {
1356 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1357 ASSERT(exceptionCode == 0);
1358 insertNodeBefore(boldElement, startNode);
1359 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1362 if (styleChange.applyItalic()) {
1363 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1364 ASSERT(exceptionCode == 0);
1365 insertNodeBefore(italicElement, startNode);
1366 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1370 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1372 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1373 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1374 EditCommandPtr split(impl);
1376 pos = Position(impl->node(), 0);
1380 // EDIT FIXME: If modified to work with the internals of applying style,
1381 // this code can work to optimize cases where a style change is taking place on
1382 // a boundary between nodes where one of the nodes has the desired style. In other
1383 // words, it is possible for content to be merged into existing nodes rather than adding
1384 // additional markup.
1385 if (currentlyHasStyle(pos))
1389 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1390 NodeImpl *nextNode = pos.node()->traverseNextNode();
1392 Position next = Position(nextNode, 0);
1393 if (currentlyHasStyle(next))
1398 // try previous node
1399 if (pos.offset() <= pos.node()->caretMinOffset()) {
1400 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1402 Position prev = Position(prevNode, prevNode->maxOffset());
1403 if (currentlyHasStyle(prev))
1412 //------------------------------------------------------------------------------------------
1413 // DeleteFromTextNodeCommand
1415 DeleteFromTextNodeCommand::DeleteFromTextNodeCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1416 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1419 ASSERT(m_offset >= 0);
1420 ASSERT(m_offset < (long)m_node->length());
1421 ASSERT(m_count >= 0);
1426 DeleteFromTextNodeCommand::~DeleteFromTextNodeCommand()
1432 void DeleteFromTextNodeCommand::doApply()
1436 int exceptionCode = 0;
1437 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1438 ASSERT(exceptionCode == 0);
1440 m_node->deleteData(m_offset, m_count, exceptionCode);
1441 ASSERT(exceptionCode == 0);
1444 void DeleteFromTextNodeCommand::doUnapply()
1447 ASSERT(!m_text.isEmpty());
1449 int exceptionCode = 0;
1450 m_node->insertData(m_offset, m_text, exceptionCode);
1451 ASSERT(exceptionCode == 0);
1454 //------------------------------------------------------------------------------------------
1455 // DeleteSelectionCommand
1457 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1458 : CompositeEditCommand(document),
1459 m_hasSelectionToDelete(false),
1460 m_smartDelete(smartDelete),
1461 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1469 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1470 : CompositeEditCommand(document),
1471 m_hasSelectionToDelete(true),
1472 m_smartDelete(smartDelete),
1473 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1474 m_selectionToDelete(selection),
1482 void DeleteSelectionCommand::initializePositionData()
1485 // Handle setting some basic positions
1487 Position start = m_selectionToDelete.start();
1488 Position end = m_selectionToDelete.end();
1490 m_upstreamStart = start.upstream(StayInBlock);
1491 m_downstreamStart = start.downstream(StayInBlock);
1492 m_upstreamEnd = end.upstream(StayInBlock);
1493 m_downstreamEnd = end.downstream(StayInBlock);
1496 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
1498 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1499 bool hasLeadingWhitespaceBeforeAdjustment = m_leadingWhitespace.isNotNull();
1500 if (m_smartDelete && hasLeadingWhitespaceBeforeAdjustment) {
1501 Position pos = VisiblePosition(start).previous().deepEquivalent();
1502 // Expand out one character upstream for smart delete and recalculate
1503 // positions based on this change.
1504 m_upstreamStart = pos.upstream(StayInBlock);
1505 m_downstreamStart = pos.downstream(StayInBlock);
1506 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1508 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1509 // Note: trailing whitespace is only considered for smart delete if there is no leading
1510 // whitespace, as in the case where you double-click the first word of a paragraph.
1511 if (m_smartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_trailingWhitespace.isNotNull()) {
1512 // Expand out one character downstream for smart delete and recalculate
1513 // positions based on this change.
1514 Position pos = VisiblePosition(end).next().deepEquivalent();
1515 m_upstreamEnd = pos.upstream(StayInBlock);
1516 m_downstreamEnd = pos.downstream(StayInBlock);
1517 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1519 m_trailingWhitespaceValid = true;
1522 // Handle setting start and end blocks and the start node.
1524 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1525 m_startBlock->ref();
1526 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1528 m_startNode = m_upstreamStart.node();
1532 // Handle detecting if the line containing the selection end is itself fully selected.
1533 // This is one of the tests that determines if block merging of content needs to be done.
1535 VisiblePosition visibleEnd(end);
1536 if (isFirstVisiblePositionOnLine(visibleEnd)) {
1537 Position previousLineStart = previousLinePosition(visibleEnd, DOWNSTREAM, 0).deepEquivalent();
1538 if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
1539 m_mergeBlocksAfterDelete = false;
1542 debugPosition("m_upstreamStart ", m_upstreamStart);
1543 debugPosition("m_downstreamStart ", m_downstreamStart);
1544 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1545 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1546 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1547 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1548 debugNode( "m_startBlock ", m_startBlock);
1549 debugNode( "m_endBlock ", m_endBlock);
1550 debugNode( "m_startNode ", m_startNode);
1553 void DeleteSelectionCommand::insertPlaceholderForAncestorBlockContent()
1555 // This code makes sure a line does not disappear when deleting in this case:
1556 // <p>foo</p>bar<p>baz</p>
1557 // Select "bar" and hit delete. If nothing is done, the line containing bar will disappear.
1558 // It needs to be held open by inserting a placeholder.
1560 // <rdar://problem/3928305> selecting an entire line and typing over causes new inserted text at top of document
1562 // The checks below detect the case where the selection contains content in an ancestor block
1563 // surrounded by child blocks.
1565 NodeImpl *upstreamBlock = m_upstreamStart.node()->enclosingBlockFlowElement();
1566 NodeImpl *beforeUpstreamBlock = m_upstreamStart.upstream().node()->enclosingBlockFlowElement();
1568 if (upstreamBlock != beforeUpstreamBlock && beforeUpstreamBlock->isAncestor(upstreamBlock)) {
1569 NodeImpl *downstreamBlock = m_downstreamEnd.node()->enclosingBlockFlowElement();
1570 NodeImpl *afterDownstreamBlock = m_downstreamEnd.downstream().node()->enclosingBlockFlowElement();
1572 if (afterDownstreamBlock != downstreamBlock && afterDownstreamBlock != upstreamBlock) {
1573 NodeImpl *block = createDefaultParagraphElement(document());
1574 insertNodeBefore(block, m_upstreamStart.node());
1575 insertBlockPlaceholderIfNeeded(block);
1576 m_endingPosition = Position(block, 0);
1581 void DeleteSelectionCommand::saveTypingStyleState()
1583 // Figure out the typing style in effect before the delete is done.
1584 // FIXME: Improve typing style.
1585 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1586 CSSComputedStyleDeclarationImpl *computedStyle = m_selectionToDelete.start().computedStyle();
1587 computedStyle->ref();
1588 m_typingStyle = computedStyle->copyInheritableProperties();
1589 m_typingStyle->ref();
1590 computedStyle->deref();
1593 bool DeleteSelectionCommand::handleSpecialCaseAllContentDelete()
1595 Position start = m_downstreamStart;
1596 Position end = m_upstreamEnd;
1598 ElementImpl *rootElement = start.node()->rootEditableElement();
1599 Position rootStart = Position(rootElement, 0);
1600 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1601 if (start == VisiblePosition(rootStart).downstreamDeepEquivalent() && end == VisiblePosition(rootEnd).deepEquivalent()) {
1602 // Delete every child of the root editable element
1603 NodeImpl *node = rootElement->firstChild();
1605 NodeImpl *next = node->traverseNextSibling();
1614 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
1616 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1617 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1618 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1619 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1620 if (isBROnLineByItself) {
1621 removeNode(m_downstreamStart.node());
1622 m_endingPosition = m_upstreamStart;
1623 m_mergeBlocksAfterDelete = false;
1627 // Check for special-case where the selection contains only a BR right after a block ended.
1628 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1629 Position upstreamFromBR = m_downstreamEnd.upstream();
1630 Position downstreamFromStart = m_downstreamStart.downstream();
1631 bool startIsBRAfterBlock = downstreamEndIsBR && downstreamFromStart.node() == m_downstreamEnd.node() &&
1632 m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamFromBR.node()->enclosingBlockFlowElement();
1633 if (startIsBRAfterBlock) {
1634 removeNode(m_downstreamEnd.node());
1635 m_endingPosition = upstreamFromBR;
1636 m_mergeBlocksAfterDelete = false;
1640 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1641 // should not be done.
1642 if (upstreamStartIsBR && downstreamStartIsBR)
1643 m_mergeBlocksAfterDelete = false;
1648 void DeleteSelectionCommand::handleGeneralDelete()
1650 int startOffset = m_upstreamStart.offset();
1652 if (startOffset == 0 && m_startNode->isBlockFlow() && m_startBlock != m_endBlock && !m_endBlock->isAncestor(m_startBlock)) {
1653 // The block containing the start of the selection is completely selected.
1654 // Delete it all in one step right here.
1655 ASSERT(!m_downstreamEnd.node()->isAncestor(m_startNode));
1657 // shift the start node to the start of the next block.
1658 NodeImpl *old = m_startNode;
1659 m_startNode = m_startBlock->traverseNextSibling();
1664 removeFullySelectedNode(m_startBlock);
1666 else if (startOffset >= m_startNode->caretMaxOffset()) {
1667 // Move the start node to the next node in the tree since the startOffset is equal to
1668 // or beyond the start node's caretMaxOffset This means there is nothing visible to delete.
1669 // However, before moving on, delete any insignificant text that may be present in a text node.
1670 if (m_startNode->isTextNode()) {
1671 // Delete any insignificant text from this node.
1672 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1673 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1674 deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1677 // shift the start node to the next
1678 NodeImpl *old = m_startNode;
1679 m_startNode = old->traverseNextNode();
1685 if (m_startNode == m_downstreamEnd.node()) {
1686 // The selection to delete is all in one node.
1687 if (!m_startNode->renderer() ||
1688 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1690 removeFullySelectedNode(m_startNode);
1692 else if (m_downstreamEnd.offset() - startOffset > 0) {
1693 // in a text node that needs to be trimmed
1694 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1695 deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
1696 m_trailingWhitespaceValid = false;
1700 // The selection to delete spans more than one node.
1701 NodeImpl *node = m_startNode;
1703 if (startOffset > 0) {
1704 // in a text node that needs to be trimmed
1705 TextImpl *text = static_cast<TextImpl *>(node);
1706 deleteTextFromNode(text, startOffset, text->length() - startOffset);
1707 node = node->traverseNextNode();
1710 // handle deleting all nodes that are completely selected
1711 while (node && node != m_downstreamEnd.node()) {
1712 if (!m_downstreamEnd.node()->isAncestor(node)) {
1713 NodeImpl *nextNode = node->traverseNextSibling();
1714 removeFullySelectedNode(node);
1718 NodeImpl *n = node->lastChild();
1719 while (n && n->lastChild())
1721 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1722 // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
1723 removeFullySelectedNode(node);
1724 m_trailingWhitespaceValid = false;
1728 node = node->traverseNextNode();
1733 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1734 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1735 // need to delete whole node
1736 // we can get here if this is the last node in the block
1737 removeFullySelectedNode(m_downstreamEnd.node());
1738 m_trailingWhitespaceValid = false;
1741 // in a text node that needs to be trimmed
1742 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1743 if (m_downstreamEnd.offset() > 0) {
1744 deleteTextFromNode(text, 0, m_downstreamEnd.offset());
1745 m_downstreamEnd = Position(text, 0);
1746 m_trailingWhitespaceValid = false;
1753 void DeleteSelectionCommand::fixupWhitespace()
1755 document()->updateLayout();
1756 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1757 LOG(Editing, "replace leading");
1758 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1759 replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1761 else if (m_trailingWhitespace.isNotNull()) {
1762 if (m_trailingWhitespaceValid) {
1763 if (!m_trailingWhitespace.isRenderedCharacter()) {
1764 LOG(Editing, "replace trailing [valid]");
1765 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1766 replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1770 Position pos = m_endingPosition.downstream(StayInBlock);
1771 pos = Position(pos.node(), pos.offset() - 1);
1772 if (isWS(pos) && !pos.isRenderedCharacter()) {
1773 LOG(Editing, "replace trailing [invalid]");
1774 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1775 replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
1776 // need to adjust ending position since the trailing position is not valid.
1777 m_endingPosition = pos;
1783 // This function moves nodes in the block containing startNode to dstBlock, starting
1784 // from startNode and proceeding to the end of the block. Nodes in the block containing
1785 // startNode that appear in document order before startNode are not moved.
1786 // This function is an important helper for deleting selections that cross block
1788 void DeleteSelectionCommand::moveNodesAfterNode()
1790 if (!m_mergeBlocksAfterDelete)
1793 if (m_endBlock == m_startBlock)
1796 NodeImpl *startNode = m_downstreamEnd.node();
1797 NodeImpl *dstNode = m_upstreamStart.node();
1799 if (!startNode->inDocument() || !dstNode->inDocument())
1802 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1803 if (isTableStructureNode(startBlock))
1804 // Do not move content between parts of a table
1807 // Now that we are about to add content, check to see if a placeholder element
1809 removeBlockPlaceholderIfNeeded(startBlock);
1811 // Move the subtree containing node
1812 NodeImpl *node = startNode->enclosingInlineElement();
1814 // Insert after the subtree containing destNode
1815 NodeImpl *refNode = dstNode->enclosingInlineElement();
1817 // Nothing to do if start is already at the beginning of dstBlock
1818 NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
1819 if (startBlock == dstBlock->firstChild())
1823 NodeImpl *rootNode = refNode->rootEditableElement();
1824 while (node && node->isAncestor(startBlock)) {
1825 NodeImpl *moveNode = node;
1826 node = node->nextSibling();
1827 removeNode(moveNode);
1828 if (refNode == rootNode)
1829 insertNodeAt(moveNode, refNode, 0);
1831 insertNodeAfter(moveNode, refNode);
1835 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1836 // to make the layout come out right. Consider this document:
1842 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1843 // move the contents of the div to the block containing 'One' and delete the div.
1844 // This will have the side effect of moving 'Three' on to the same line as 'One'
1845 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1846 // This may not be ideal, but it is better than nothing.
1847 document()->updateLayout();
1848 if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
1849 removeNode(startBlock);
1850 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1851 insertNodeAfter(createBreakElement(document()), refNode);
1856 void DeleteSelectionCommand::calculateEndingPosition()
1858 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1861 m_endingPosition = m_upstreamStart;
1862 if (m_endingPosition.node()->inDocument())
1865 m_endingPosition = m_downstreamEnd;
1866 if (m_endingPosition.node()->inDocument())
1869 m_endingPosition = Position(m_startBlock, 0);
1870 if (m_endingPosition.node()->inDocument())
1873 m_endingPosition = Position(m_endBlock, 0);
1874 if (m_endingPosition.node()->inDocument())
1877 m_endingPosition = Position(document()->documentElement(), 0);
1880 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1882 // Compute the difference between the style before the delete and the style now
1883 // after the delete has been done. Set this style on the part, so other editing
1884 // commands being composed with this one will work, and also cache it on the command,
1885 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1887 // FIXME: Improve typing style.
1888 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1889 if (m_startNode == m_endingPosition.node())
1890 document()->part()->setTypingStyle(0);
1892 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1893 endingStyle.diff(m_typingStyle);
1894 if (!m_typingStyle->length()) {
1895 m_typingStyle->deref();
1898 document()->part()->setTypingStyle(m_typingStyle);
1899 setTypingStyle(m_typingStyle);
1903 void DeleteSelectionCommand::clearTransientState()
1905 m_selectionToDelete.clear();
1906 m_upstreamStart.clear();
1907 m_downstreamStart.clear();
1908 m_upstreamEnd.clear();
1909 m_downstreamEnd.clear();
1910 m_endingPosition.clear();
1911 m_leadingWhitespace.clear();
1912 m_trailingWhitespace.clear();
1915 m_startBlock->deref();
1919 m_endBlock->deref();
1923 m_startNode->deref();
1926 if (m_typingStyle) {
1927 m_typingStyle->deref();
1932 void DeleteSelectionCommand::doApply()
1934 // If selection has not been set to a custom selection when the command was created,
1935 // use the current ending selection.
1936 if (!m_hasSelectionToDelete)
1937 m_selectionToDelete = endingSelection();
1939 if (!m_selectionToDelete.isRange())
1942 initializePositionData();
1944 if (!m_startBlock || !m_endBlock) {
1945 // Can't figure out what blocks we're in. This can happen if
1946 // the document structure is not what we are expecting, like if
1947 // the document has no body element, or if the editable block
1948 // has been changed to display: inline. Some day it might
1949 // be nice to be able to deal with this, but for now, bail.
1950 clearTransientState();
1954 // Delete any text that may hinder our ability to fixup whitespace after the detele
1955 deleteInsignificantTextDownstream(m_trailingWhitespace);
1957 saveTypingStyleState();
1958 insertPlaceholderForAncestorBlockContent();
1960 if (!handleSpecialCaseAllContentDelete())
1961 if (!handleSpecialCaseBRDelete())
1962 handleGeneralDelete();
1964 // Do block merge if start and end of selection are in different blocks.
1965 moveNodesAfterNode();
1967 calculateEndingPosition();
1970 // If the delete emptied a block, add in a placeholder so the block does not
1971 // seem to disappear.
1972 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1973 calculateTypingStyleAfterDelete();
1974 setEndingSelection(m_endingPosition);
1975 debugPosition("endingPosition ", m_endingPosition);
1976 clearTransientState();
1977 rebalanceWhitespace();
1980 EditAction DeleteSelectionCommand::editingAction() const
1982 // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
1983 // but in that case there's a TypingCommand that supplies the editingAction(), so
1984 // the Undo menu correctly shows "Undo Typing"
1985 return EditActionCut;
1988 bool DeleteSelectionCommand::preservesTypingStyle() const
1993 //------------------------------------------------------------------------------------------
1994 // InsertIntoTextNode
1996 InsertIntoTextNode::InsertIntoTextNode(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
1997 : EditCommand(document), m_node(node), m_offset(offset)
2000 ASSERT(m_offset >= 0);
2001 ASSERT(!text.isEmpty());
2004 m_text = text.copy(); // make a copy to ensure that the string never changes
2007 InsertIntoTextNode::~InsertIntoTextNode()
2013 void InsertIntoTextNode::doApply()
2016 ASSERT(m_offset >= 0);
2017 ASSERT(!m_text.isEmpty());
2019 int exceptionCode = 0;
2020 m_node->insertData(m_offset, m_text, exceptionCode);
2021 ASSERT(exceptionCode == 0);
2024 void InsertIntoTextNode::doUnapply()
2027 ASSERT(m_offset >= 0);
2028 ASSERT(!m_text.isEmpty());
2030 int exceptionCode = 0;
2031 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
2032 ASSERT(exceptionCode == 0);
2035 //------------------------------------------------------------------------------------------
2036 // InsertLineBreakCommand
2038 InsertLineBreakCommand::InsertLineBreakCommand(DocumentImpl *document)
2039 : CompositeEditCommand(document)
2043 void InsertLineBreakCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
2045 // Insert the BR after the caret position. In the case the
2046 // position is a block, do an append. We don't want to insert
2047 // the BR *after* the block.
2048 Position upstream(pos.upstream(StayInBlock));
2049 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2050 if (cb == pos.node())
2051 appendNode(node, cb);
2053 insertNodeAfter(node, pos.node());
2056 void InsertLineBreakCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
2058 // Insert the BR after the caret position. In the case the
2059 // position is a block, do an append. We don't want to insert
2060 // the BR *before* the block.
2061 Position upstream(pos.upstream(StayInBlock));
2062 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2063 if (cb == pos.node())
2064 appendNode(node, cb);
2066 insertNodeBefore(node, pos.node());
2069 void InsertLineBreakCommand::doApply()
2072 Selection selection = endingSelection();
2074 ElementImpl *breakNode = createBreakElement(document());
2075 NodeImpl *nodeToInsert = breakNode;
2077 // Handle the case where there is a typing style.
2078 // FIXME: Improve typing style.
2079 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2080 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2081 if (typingStyle && typingStyle->length() > 0)
2082 nodeToInsert = applyTypingStyle(breakNode);
2084 Position pos(selection.start().upstream(StayInBlock));
2085 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
2086 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
2087 bool atEndOfBlock = isLastVisiblePositionInBlock(VisiblePosition(pos));
2090 LOG(Editing, "input newline case 1");
2091 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
2092 // This makes the "real" BR we want to insert appear in the rendering without any
2093 // significant side effects (and no real worries either since you can't arrow past
2095 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
2096 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
2097 insertNodeBefore(nodeToInsert, pos.node());
2100 NodeImpl *next = pos.node()->traverseNextNode();
2101 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
2102 insertNodeAfterPosition(nodeToInsert, pos);
2103 if (hasTrailingBR) {
2104 setEndingSelection(Position(next, 0));
2106 else if (!document()->inStrictMode()) {
2107 // Insert an "extra" BR at the end of the block.
2108 ElementImpl *extraBreakNode = createBreakElement(document());
2109 insertNodeAfter(extraBreakNode, nodeToInsert);
2110 setEndingSelection(Position(extraBreakNode, 0));
2115 LOG(Editing, "input newline case 2");
2116 // Insert node before downstream position, and place caret there as well.
2117 Position endingPosition = pos.downstream(StayInBlock);
2118 insertNodeBeforePosition(nodeToInsert, endingPosition);
2119 setEndingSelection(endingPosition);
2122 LOG(Editing, "input newline case 3");
2123 // Insert BR after this node. Place caret in the position that is downstream
2124 // of the current position, reckoned before inserting the BR in between.
2125 Position endingPosition = pos.downstream(StayInBlock);
2126 insertNodeAfterPosition(nodeToInsert, pos);
2127 setEndingSelection(endingPosition);
2130 // Split a text node
2131 LOG(Editing, "input newline case 4");
2132 ASSERT(pos.node()->isTextNode());
2135 int exceptionCode = 0;
2136 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2137 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
2138 deleteTextFromNode(textNode, 0, pos.offset());
2139 insertNodeBefore(textBeforeNode, textNode);
2140 insertNodeBefore(nodeToInsert, textNode);
2141 Position endingPosition = Position(textNode, 0);
2143 // Handle whitespace that occurs after the split
2144 document()->updateLayout();
2145 if (!endingPosition.isRenderedCharacter()) {
2146 // Clear out all whitespace and insert one non-breaking space
2147 deleteInsignificantTextDownstream(endingPosition);
2148 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
2151 setEndingSelection(endingPosition);
2153 rebalanceWhitespace();
2156 //------------------------------------------------------------------------------------------
2157 // InsertNodeBeforeCommand
2159 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2160 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2162 ASSERT(m_insertChild);
2163 m_insertChild->ref();
2169 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2171 ASSERT(m_insertChild);
2172 m_insertChild->deref();
2175 m_refChild->deref();
2178 void InsertNodeBeforeCommand::doApply()
2180 ASSERT(m_insertChild);
2182 ASSERT(m_refChild->parentNode());
2184 int exceptionCode = 0;
2185 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2186 ASSERT(exceptionCode == 0);
2189 void InsertNodeBeforeCommand::doUnapply()
2191 ASSERT(m_insertChild);
2193 ASSERT(m_refChild->parentNode());
2195 int exceptionCode = 0;
2196 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2197 ASSERT(exceptionCode == 0);
2200 //------------------------------------------------------------------------------------------
2201 // InsertParagraphSeparatorCommand
2203 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(DocumentImpl *document)
2204 : CompositeEditCommand(document)
2208 InsertParagraphSeparatorCommand::~InsertParagraphSeparatorCommand()
2210 derefNodesInList(clonedNodes);
2213 ElementImpl *InsertParagraphSeparatorCommand::createParagraphElement()
2215 ElementImpl *element = createDefaultParagraphElement(document());
2217 clonedNodes.append(element);
2221 void InsertParagraphSeparatorCommand::doApply()
2223 Selection selection = endingSelection();
2224 if (selection.isNone())
2227 // Delete the current selection.
2228 // If the selection is a range and the start and end nodes are in different blocks,
2229 // then this command bails after the delete, but takes the one additional step of
2230 // moving the selection downstream so it is in the ending block (if that block is
2231 // still around, that is).
2232 Position pos = selection.start();
2233 if (selection.isRange()) {
2234 NodeImpl *startBlockBeforeDelete = selection.start().node()->enclosingBlockFlowElement();
2235 NodeImpl *endBlockBeforeDelete = selection.end().node()->enclosingBlockFlowElement();
2236 bool doneAfterDelete = startBlockBeforeDelete != endBlockBeforeDelete;
2237 deleteSelection(false, false);
2238 if (doneAfterDelete) {
2239 document()->updateLayout();
2240 setEndingSelection(endingSelection().start().downstream());
2241 rebalanceWhitespace();
2244 pos = endingSelection().start();
2247 // Find the start block.
2248 NodeImpl *startNode = pos.node();
2249 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
2250 if (!startBlock || !startBlock->parentNode())
2253 VisiblePosition visiblePos(pos);
2254 bool isFirstInBlock = isFirstVisiblePositionInBlock(visiblePos);
2255 bool isLastInBlock = isLastVisiblePositionInBlock(visiblePos);
2256 bool startBlockIsRoot = startBlock == startBlock->rootEditableElement();
2258 // This is the block that is going to be inserted.
2259 NodeImpl *blockToInsert = startBlockIsRoot ? createParagraphElement() : startBlock->cloneNode(false);
2261 //---------------------------------------------------------------------
2262 // Handle empty block case.
2263 if (isFirstInBlock && isLastInBlock) {
2264 LOG(Editing, "insert paragraph separator: empty block case");
2265 if (startBlockIsRoot) {
2266 NodeImpl *extraBlock = createParagraphElement();
2267 appendNode(extraBlock, startBlock);
2268 insertBlockPlaceholderIfNeeded(extraBlock);
2269 appendNode(blockToInsert, startBlock);
2272 insertNodeAfter(blockToInsert, startBlock);
2274 insertBlockPlaceholderIfNeeded(blockToInsert);
2275 setEndingSelection(Position(blockToInsert, 0));
2279 //---------------------------------------------------------------------
2280 // Handle case when position is in the first visible position in its block.
2281 // and similar case where upstream position is in another block.
2282 bool upstreamInDifferentBlock = startBlock != pos.upstream(DoNotStayInBlock).node()->enclosingBlockFlowElement();
2283 if (upstreamInDifferentBlock || isFirstInBlock) {
2284 LOG(Editing, "insert paragraph separator: first in block case");
2285 pos = pos.downstream(StayInBlock);
2286 NodeImpl *refNode = isFirstInBlock && !startBlockIsRoot ? startBlock : pos.node();
2287 insertNodeBefore(blockToInsert, refNode);
2288 insertBlockPlaceholderIfNeeded(blockToInsert);
2289 setEndingSelection(pos);
2293 //---------------------------------------------------------------------
2294 // Handle case when position is in the last visible position in its block,
2295 // and similar case where downstream position is in another block.
2296 bool downstreamInDifferentBlock = startBlock != pos.downstream(DoNotStayInBlock).node()->enclosingBlockFlowElement();
2297 if (downstreamInDifferentBlock || isLastInBlock) {
2298 LOG(Editing, "insert paragraph separator: last in block case");
2299 NodeImpl *refNode = isLastInBlock && !startBlockIsRoot ? startBlock : pos.node();
2300 insertNodeAfter(blockToInsert, refNode);
2301 insertBlockPlaceholderIfNeeded(blockToInsert);
2302 setEndingSelection(Position(blockToInsert, 0));
2306 //---------------------------------------------------------------------
2307 // Handle the (more complicated) general case,
2309 LOG(Editing, "insert paragraph separator: general case");
2311 // Check if pos.node() is a <br>. If it is, and the document is in quirks mode,
2312 // then this <br> will collapse away when we add a block after it. Add an extra <br>.
2313 if (!document()->inStrictMode()) {
2314 Position downstreamPos = pos.downstream(StayInBlock);
2315 if (downstreamPos.node()->id() == ID_BR) {
2316 NodeImpl *extraBreak = createBreakElement(document());
2317 insertNodeAfter(extraBreak, downstreamPos.node());
2320 Position upstreamPos = pos.upstream(StayInBlock);
2321 if (upstreamPos.node()->id() == ID_BR)
2322 insertNodeAfter(createBreakElement(document()), upstreamPos.node());
2323 // leave pos where it is
2327 // Build up list of ancestors in between the start node and the start block.
2328 if (startNode != startBlock) {
2329 for (NodeImpl *n = startNode->parentNode(); n && n != startBlock; n = n->parentNode())
2330 ancestors.prepend(n);
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 // Put the added block in the tree.
2355 if (startBlockIsRoot) {
2356 NodeImpl *lastSibling = pos.node();
2357 while (lastSibling->nextSibling())
2358 lastSibling = lastSibling->nextSibling();
2359 insertNodeAfter(blockToInsert, lastSibling);
2362 insertNodeAfter(blockToInsert, startBlock);
2365 // Make clones of ancestors in between the start node and the start block.
2366 NodeImpl *parent = blockToInsert;
2367 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2368 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2370 clonedNodes.append(child);
2371 appendNode(child, parent);
2375 // Move the start node and the siblings of the start node.
2376 if (startNode != startBlock) {
2377 NodeImpl *n = startNode;
2378 if (n->id() == ID_BR)
2379 n = n->nextSibling();
2380 while (n && n != blockToInsert) {
2381 NodeImpl *next = n->nextSibling();
2383 appendNode(n, parent);
2388 // Move everything after the start node.
2389 NodeImpl *leftParent = ancestors.last();
2390 while (leftParent && leftParent != startBlock) {
2391 parent = parent->parentNode();
2392 NodeImpl *n = leftParent->nextSibling();
2394 NodeImpl *next = n->nextSibling();
2396 appendNode(n, parent);
2399 leftParent = leftParent->parentNode();
2402 setEndingSelection(Position(blockToInsert, 0));
2403 rebalanceWhitespace();
2406 //------------------------------------------------------------------------------------------
2407 // InsertParagraphSeparatorInQuotedContentCommand
2409 InsertParagraphSeparatorInQuotedContentCommand::InsertParagraphSeparatorInQuotedContentCommand(DocumentImpl *document)
2410 : CompositeEditCommand(document)
2414 InsertParagraphSeparatorInQuotedContentCommand::~InsertParagraphSeparatorInQuotedContentCommand()
2416 derefNodesInList(clonedNodes);
2418 m_breakNode->deref();
2421 bool InsertParagraphSeparatorInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
2423 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
2426 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
2429 void InsertParagraphSeparatorInQuotedContentCommand::doApply()
2431 Selection selection = endingSelection();
2432 if (selection.isNone())
2435 // Delete the current selection.
2436 Position pos = selection.start();
2437 if (selection.isRange()) {
2438 deleteSelection(false, false);
2439 pos = endingSelection().start().upstream();
2442 // Find the top-most blockquote from the start.
2443 NodeImpl *startNode = pos.node();
2444 NodeImpl *topBlockquote = 0;
2445 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
2446 if (isMailBlockquote(n))
2449 if (!topBlockquote || !topBlockquote->parentNode())
2452 // Build up list of ancestors in between the start node and the top blockquote.
2453 if (startNode != topBlockquote) {
2454 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
2455 ancestors.prepend(n);
2458 // Insert a break after the top blockquote.
2459 m_breakNode = createBreakElement(document());
2461 insertNodeAfter(m_breakNode, topBlockquote);
2463 if (!isLastVisiblePositionInNode(VisiblePosition(pos), topBlockquote)) {
2464 // Split at pos if in the middle of a text node.
2465 if (startNode->isTextNode()) {
2466 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2467 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2468 if (pos.offset() > 0 && !atEnd) {
2469 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2470 EditCommandPtr cmd(splitCommand);
2471 applyCommandToComposite(cmd);
2472 startNode = splitCommand->node();
2473 pos = Position(startNode, 0);
2476 startNode = startNode->traverseNextNode();
2480 else if (pos.offset() > 0) {
2481 startNode = startNode->traverseNextNode();
2485 // Insert a clone of the top blockquote after the break.
2486 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2487 clonedBlockquote->ref();
2488 clonedNodes.append(clonedBlockquote);
2489 insertNodeAfter(clonedBlockquote, m_breakNode);
2490 insertBlockPlaceholderIfNeeded(clonedBlockquote);
2492 // Make clones of ancestors in between the start node and the top blockquote.
2493 NodeImpl *parent = clonedBlockquote;
2494 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2495 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2497 clonedNodes.append(child);
2498 appendNode(child, parent);
2502 // Move the start node and the siblings of the start node.
2503 bool startIsBR = false;
2504 if (startNode != topBlockquote) {
2505 NodeImpl *n = startNode;
2506 bool startIsBR = n->id() == ID_BR;
2508 n = n->nextSibling();
2510 NodeImpl *next = n->nextSibling();
2512 appendNode(n, parent);
2517 // Move everything after the start node.
2518 NodeImpl *leftParent = ancestors.last();
2522 leftParent = topBlockquote;
2523 ElementImpl *b = createBreakElement(document());
2525 clonedNodes.append(b);
2526 appendNode(b, leftParent);
2529 leftParent = ancestors.last();
2530 while (leftParent && leftParent != topBlockquote) {
2531 parent = parent->parentNode();
2532 NodeImpl *n = leftParent->nextSibling();
2534 NodeImpl *next = n->nextSibling();
2536 appendNode(n, parent);
2539 leftParent = leftParent->parentNode();
2543 // Put the selection right before the break.
2544 setEndingSelection(Position(m_breakNode, 0));
2545 rebalanceWhitespace();
2548 //------------------------------------------------------------------------------------------
2549 // InsertTextCommand
2551 InsertTextCommand::InsertTextCommand(DocumentImpl *document)
2552 : CompositeEditCommand(document), m_charactersAdded(0)
2556 void InsertTextCommand::doApply()
2560 void InsertTextCommand::deleteCharacter()
2562 ASSERT(state() == Applied);
2564 Selection selection = endingSelection();
2566 if (!selection.start().node()->isTextNode())
2569 int exceptionCode = 0;
2570 int offset = selection.start().offset() - 1;
2571 if (offset >= selection.start().node()->caretMinOffset()) {
2572 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2573 textNode->deleteData(offset, 1, exceptionCode);
2574 ASSERT(exceptionCode == 0);
2575 selection = Selection(Position(textNode, offset));
2576 setEndingSelection(selection);
2577 m_charactersAdded--;
2581 Position InsertTextCommand::prepareForTextInsertion(bool adjustDownstream)
2583 // Prepare for text input by looking at the current position.
2584 // It may be necessary to insert a text node to receive characters.
2585 Selection selection = endingSelection();
2586 ASSERT(selection.isCaret());
2588 Position pos = selection.start();
2589 if (adjustDownstream)
2590 pos = pos.downstream(StayInBlock);
2592 pos = pos.upstream(StayInBlock);
2594 if (!pos.node()->isTextNode()) {
2595 NodeImpl *textNode = document()->createEditingTextNode("");
2596 NodeImpl *nodeToInsert = textNode;
2598 // Handle the case where there is a typing style.
2599 // FIXME: Improve typing style.
2600 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2601 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2602 if (typingStyle && typingStyle->length() > 0)
2603 nodeToInsert = applyTypingStyle(textNode);
2605 // Now insert the node in the right place
2606 if (pos.node()->isEditableBlock()) {
2607 LOG(Editing, "prepareForTextInsertion case 1");
2608 appendNode(nodeToInsert, pos.node());
2610 else if (pos.node()->caretMinOffset() == pos.offset()) {
2611 LOG(Editing, "prepareForTextInsertion case 2");
2612 insertNodeBefore(nodeToInsert, pos.node());
2614 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2615 LOG(Editing, "prepareForTextInsertion case 3");
2616 insertNodeAfter(nodeToInsert, pos.node());
2619 ASSERT_NOT_REACHED();
2621 pos = Position(textNode, 0);
2624 // Handle the case where there is a typing style.
2625 // FIXME: Improve typing style.
2626 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2627 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2628 if (typingStyle && typingStyle->length() > 0) {
2629 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2630 // Need to split current text node in order to insert a span.
2631 TextImpl *text = static_cast<TextImpl *>(pos.node());
2632 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2633 EditCommandPtr cmd(impl);
2634 applyCommandToComposite(cmd);
2635 setEndingSelection(Position(impl->node(), 0));
2638 TextImpl *editingTextNode = document()->createEditingTextNode("");
2639 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2640 if (node->isBlockFlow())
2641 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2643 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2644 pos = Position(editingTextNode, 0);
2650 void InsertTextCommand::input(const DOMString &text, bool selectInsertedText)
2652 Selection selection = endingSelection();
2653 bool adjustDownstream = isFirstVisiblePositionOnLine(VisiblePosition(selection.start().downstream(StayInBlock)));
2655 // Delete the current selection, or collapse whitespace, as needed
2656 if (selection.isRange())
2659 // Delete any insignificant text that could get in the way of whitespace turning
2660 // out correctly after the insertion.
2661 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2663 // Make sure the document is set up to receive text
2664 Position pos = prepareForTextInsertion(adjustDownstream);
2666 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2667 long offset = pos.offset();
2669 // Now that we are about to add content, check to see if a placeholder element
2671 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2673 // These are temporary implementations for inserting adjoining spaces
2674 // into a document. We are working on a CSS-related whitespace solution
2675 // that will replace this some day. We hope.
2677 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2678 // although the number of spaces varies (we choose four spaces).
2679 // Note that there is no attempt to make this work like a real tab stop, it is merely
2680 // a set number of spaces. This also seems to be the HTML editing convention.
2681 for (int i = 0; i < spacesPerTab; i++) {
2682 insertSpace(textNode, offset);
2683 rebalanceWhitespace();
2684 document()->updateLayout();
2686 if (selectInsertedText)
2687 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2689 setEndingSelection(Position(textNode, offset + spacesPerTab));
2690 m_charactersAdded += spacesPerTab;
2692 else if (isWS(text)) {
2693 insertSpace(textNode, offset);
2694 if (selectInsertedText)
2695 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2697 setEndingSelection(Position(textNode, offset + 1));
2698 m_charactersAdded++;
2699 rebalanceWhitespace();
2702 const DOMString &existingText = textNode->data();
2703 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2704 // DOM looks like this:
2705 // character nbsp caret
2706 // As we are about to insert a non-whitespace character at the caret
2707 // convert the nbsp to a regular space.
2708 // EDIT FIXME: This needs to be improved some day to convert back only
2709 // those nbsp's added by the editor to make rendering come out right.
2710 replaceTextInNode(textNode, offset - 1, 1, " ");
2712 insertTextIntoNode(textNode, offset, text);
2713 if (selectInsertedText)
2714 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2716 setEndingSelection(Position(textNode, offset + text.length()));
2717 m_charactersAdded += text.length();
2721 void InsertTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2725 DOMString text(textNode->data());
2727 // count up all spaces and newlines in front of the caret
2728 // delete all collapsed ones
2729 // this will work out OK since the offset we have been passed has been upstream-ized
2731 for (unsigned int i = offset; i < text.length(); i++) {
2738 // By checking the character at the downstream position, we can
2739 // check if there is a rendered WS at the caret
2740 Position pos(textNode, offset);
2741 Position downstream = pos.downstream();
2742 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2743 count--; // leave this WS in
2745 deleteTextFromNode(textNode, offset, count);
2748 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2749 // insert a "regular" space
2750 insertTextIntoNode(textNode, offset, " ");
2754 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2755 // DOM looks like this:
2757 // insert a space between the two nbsps
2758 insertTextIntoNode(textNode, offset - 1, " ");
2763 insertTextIntoNode(textNode, offset, nonBreakingSpaceString());
2766 bool InsertTextCommand::isInsertTextCommand() const
2771 //------------------------------------------------------------------------------------------
2772 // JoinTextNodesCommand
2774 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2775 : EditCommand(document), m_text1(text1), m_text2(text2)
2779 ASSERT(m_text1->nextSibling() == m_text2);
2780 ASSERT(m_text1->length() > 0);
2781 ASSERT(m_text2->length() > 0);
2787 JoinTextNodesCommand::~JoinTextNodesCommand()
2795 void JoinTextNodesCommand::doApply()
2799 ASSERT(m_text1->nextSibling() == m_text2);
2801 int exceptionCode = 0;
2802 m_text2->insertData(0, m_text1->data(), exceptionCode);
2803 ASSERT(exceptionCode == 0);
2805 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2806 ASSERT(exceptionCode == 0);
2808 m_offset = m_text1->length();
2811 void JoinTextNodesCommand::doUnapply()
2814 ASSERT(m_offset > 0);
2816 int exceptionCode = 0;
2818 m_text2->deleteData(0, m_offset, exceptionCode);
2819 ASSERT(exceptionCode == 0);
2821 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2822 ASSERT(exceptionCode == 0);
2824 ASSERT(m_text2->previousSibling()->isTextNode());
2825 ASSERT(m_text2->previousSibling() == m_text1);
2828 //------------------------------------------------------------------------------------------
2829 // MoveSelectionCommand
2831 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2832 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2838 MoveSelectionCommand::~MoveSelectionCommand()
2841 m_fragment->deref();
2844 void MoveSelectionCommand::doApply()
2846 Selection selection = endingSelection();
2847 ASSERT(selection.isRange());
2849 Position pos = m_position;
2851 // Update the position otherwise it may become invalid after the selection is deleted.
2852 NodeImpl *positionNode = m_position.node();
2853 long positionOffset = m_position.offset();
2854 Position selectionEnd = selection.end();
2855 long selectionEndOffset = selectionEnd.offset();
2856 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2857 positionOffset -= selectionEndOffset;
2858 Position selectionStart = selection.start();
2859 if (selectionStart.node() == positionNode) {
2860 positionOffset += selectionStart.offset();
2862 pos = Position(positionNode, positionOffset);
2865 deleteSelection(m_smartMove);
2867 // If the node for the destination has been removed as a result of the deletion,
2868 // set the destination to the ending point after the deletion.
2869 // Fixes: <rdar://problem/3910425> REGRESSION (Mail): Crash in ReplaceSelectionCommand;
2870 // selection is empty, leading to null deref
2871 if (!pos.node()->inDocument())
2872 pos = endingSelection().start();
2874 setEndingSelection(pos);
2875 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2876 applyCommandToComposite(cmd);
2879 EditAction MoveSelectionCommand::editingAction() const
2881 return EditActionDrag;
2884 //------------------------------------------------------------------------------------------
2885 // RebalanceWhitespaceCommand
2887 RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(DocumentImpl *document, const Position &pos)
2888 : EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset), m_downstreamOffset(InvalidOffset)
2892 RebalanceWhitespaceCommand::~RebalanceWhitespaceCommand()
2896 void RebalanceWhitespaceCommand::doApply()
2898 static DOMString space(" ");
2900 if (m_position.isNull() || !m_position.node()->isTextNode())
2903 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2904 DOMString text = textNode->data();
2905 if (text.length() == 0)
2908 // find upstream offset
2909 long upstream = m_position.offset();
2910 while (upstream > 0 && isWS(text[upstream - 1]) || isNBSP(text[upstream - 1])) {
2912 m_upstreamOffset = upstream;
2915 // find downstream offset
2916 long downstream = m_position.offset();
2917 while ((unsigned)downstream < text.length() && isWS(text[downstream]) || isNBSP(text[downstream])) {
2919 m_downstreamOffset = downstream;
2922 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2925 m_upstreamOffset = upstream;
2926 m_downstreamOffset = downstream;
2927 long length = m_downstreamOffset - m_upstreamOffset;
2929 m_beforeString = text.substring(m_upstreamOffset, length);
2931 // The following loop figures out a "rebalanced" whitespace string for any length
2932 // string, and takes into account the special cases that need to handled for the
2933 // start and end of strings (i.e. first and last character must be an nbsp.
2934 long i = m_upstreamOffset;
2935 while (i < m_downstreamOffset) {
2936 long add = (m_downstreamOffset - i) % 3;
2939 m_afterString += nonBreakingSpaceString();
2940 m_afterString += space;
2941 m_afterString += nonBreakingSpaceString();
2945 if (i == 0 || (unsigned)i + 1 == text.length()) // at start or end of string
2946 m_afterString += nonBreakingSpaceString();
2948 m_afterString += space;
2951 if ((unsigned)i + 2 == text.length()) {
2953 m_afterString += nonBreakingSpaceString();
2954 m_afterString += nonBreakingSpaceString();
2957 m_afterString += nonBreakingSpaceString();
2958 m_afterString += space;
2965 text.remove(m_upstreamOffset, length);
2966 text.insert(m_afterString, m_upstreamOffset);
2969 void RebalanceWhitespaceCommand::doUnapply()
2971 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2974 ASSERT(m_position.node()->isTextNode());
2975 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2976 DOMString text = textNode->data();
2977 text.remove(m_upstreamOffset, m_afterString.length());
2978 text.insert(m_beforeString, m_upstreamOffset);
2981 bool RebalanceWhitespaceCommand::preservesTypingStyle() const
2986 //------------------------------------------------------------------------------------------
2987 // RemoveCSSPropertyCommand
2989 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2990 : EditCommand(document), m_decl(decl->makeMutable()), m_property(property), m_important(false)
2996 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
3002 void RemoveCSSPropertyCommand::doApply()
3006 m_oldValue = m_decl->getPropertyValue(m_property);
3007 ASSERT(!m_oldValue.isNull());
3009 m_important = m_decl->getPropertyPriority(m_property);
3010 m_decl->removeProperty(m_property);
3013 void RemoveCSSPropertyCommand::doUnapply()
3016 ASSERT(!m_oldValue.isNull());
3018 m_decl->setProperty(m_property, m_oldValue, m_important);
3021 //------------------------------------------------------------------------------------------
3022 // RemoveNodeAttributeCommand
3024 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
3025 : EditCommand(document), m_element(element), m_attribute(attribute)
3031 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
3037 void RemoveNodeAttributeCommand::doApply()
3041 m_oldValue = m_element->getAttribute(m_attribute);
3042 ASSERT(!m_oldValue.isNull());
3044 int exceptionCode = 0;
3045 m_element->removeAttribute(m_attribute, exceptionCode);
3046 ASSERT(exceptionCode == 0);
3049 void RemoveNodeAttributeCommand::doUnapply()
3052 ASSERT(!m_oldValue.isNull());
3054 int exceptionCode = 0;
3055 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
3056 ASSERT(exceptionCode == 0);
3059 //------------------------------------------------------------------------------------------
3060 // RemoveNodeCommand
3062 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
3063 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
3065 ASSERT(m_removeChild);
3066 m_removeChild->ref();
3068 m_parent = m_removeChild->parentNode();
3072 m_refChild = m_removeChild->nextSibling();
3077 RemoveNodeCommand::~RemoveNodeCommand()
3082 ASSERT(m_removeChild);
3083 m_removeChild->deref();
3086 m_refChild->deref();
3089 void RemoveNodeCommand::doApply()
3092 ASSERT(m_removeChild);
3094 int exceptionCode = 0;
3095 m_parent->removeChild(m_removeChild, exceptionCode);
3096 ASSERT(exceptionCode == 0);
3099 void RemoveNodeCommand::doUnapply()
3102 ASSERT(m_removeChild);
3104 int exceptionCode = 0;
3105 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
3106 ASSERT(exceptionCode == 0);
3109 //------------------------------------------------------------------------------------------
3110 // RemoveNodePreservingChildrenCommand
3112 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
3113 : CompositeEditCommand(document), m_node(node)
3119 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
3125 void RemoveNodePreservingChildrenCommand::doApply()
3127 while (NodeImpl* curr = node()->firstChild()) {
3129 insertNodeBefore(curr, node());
3134 //------------------------------------------------------------------------------------------
3135 // ReplaceSelectionCommand
3137 ReplacementFragment::ReplacementFragment(DocumentFragmentImpl *fragment)
3138 : m_fragment(fragment), m_hasInterchangeNewline(false), m_hasMoreThanOneBlock(false)
3141 m_type = EmptyFragment;
3147 NodeImpl *firstChild = m_fragment->firstChild();
3148 NodeImpl *lastChild = m_fragment->lastChild();
3151 m_type = EmptyFragment;
3155 if (firstChild == lastChild && firstChild->isTextNode()) {
3156 m_type = SingleTextNodeFragment;
3160 m_type = TreeFragment;
3162 NodeImpl *node = firstChild;
3163 int realBlockCount = 0;
3164 NodeImpl *nodeToDelete = 0;
3166 NodeImpl *next = node->traverseNextNode();
3167 if (isInterchangeNewlineNode(node)) {
3168 m_hasInterchangeNewline = true;
3169 nodeToDelete = node;
3171 else if (isInterchangeConvertedSpaceSpan(node)) {
3173 while ((n = node->firstChild())) {
3176 insertNodeBefore(n, node);
3181 next = n->traverseNextNode();
3183 else if (isProbablyBlock(node))
3189 removeNode(nodeToDelete);
3191 int blockCount = realBlockCount;
3192 firstChild = m_fragment->firstChild();
3193 lastChild = m_fragment->lastChild();
3194 if (!isProbablyBlock(firstChild))
3196 if (!isProbablyBlock(lastChild) && realBlockCount > 0)
3200 m_hasMoreThanOneBlock = true;
3203 ReplacementFragment::~ReplacementFragment()
3206 m_fragment->deref();
3209 NodeImpl *ReplacementFragment::firstChild() const
3211 return m_fragment->firstChild();
3214 NodeImpl *ReplacementFragment::lastChild() const
3216 return m_fragment->lastChild();
3219 NodeImpl *ReplacementFragment::mergeStartNode() const
3221 NodeImpl *node = m_fragment->firstChild();
3224 if (!isProbablyBlock(node))
3226 return node->firstChild();
3229 NodeImpl *ReplacementFragment::mergeEndNode() const
3231 NodeImpl *node = m_fragment->lastChild();
3232 while (node && node->lastChild())
3233 node = node->lastChild();
3235 if (isProbablyBlock(node))
3238 NodeImpl *startingBlock = enclosingBlock(node);
3239 ASSERT(startingBlock != node);
3241 NodeImpl *prev = node->traversePreviousNode();
3242 if (prev == m_fragment || prev == startingBlock || enclosingBlock(prev) != startingBlock)
3250 void ReplacementFragment::pruneEmptyNodes()
3255 NodeImpl *node = m_fragment->firstChild();
3257 if ((node->isTextNode() && static_cast<TextImpl *>(node)->length() == 0) ||
3258 (isProbablyBlock(node) && node->childNodeCount() == 0)) {
3259 NodeImpl *next = node->traverseNextSibling();
3265 node = node->traverseNextNode();
3271 bool ReplacementFragment::isInterchangeNewlineNode(const NodeImpl *node)
3273 static DOMString interchangeNewlineClassString(AppleInterchangeNewline);
3274 return node && node->id() == ID_BR && static_cast<const ElementImpl *>(node)->getAttribute(ATTR_CLASS) == interchangeNewlineClassString;
3277 bool ReplacementFragment::isInterchangeConvertedSpaceSpan(const NodeImpl *node)
3279 static DOMString convertedSpaceSpanClassString(AppleConvertedSpace);
3280 return node->isHTMLElement() && static_cast<const HTMLElementImpl *>(node)->getAttribute(ATTR_CLASS) == convertedSpaceSpanClassString;
3283 NodeImpl *ReplacementFragment::enclosingBlock(NodeImpl *node) const
3285 while (node && !isProbablyBlock(node))
3286 node = node->parentNode();
3287 return node ? node : m_fragment;
3290 void ReplacementFragment::removeNode(NodeImpl *node)
3295 NodeImpl *parent = node->parentNode();
3299 int exceptionCode = 0;
3300 parent->removeChild(node, exceptionCode);
3301 ASSERT(exceptionCode == 0);
3304 void ReplacementFragment::insertNodeBefore(NodeImpl *node, NodeImpl *refNode)
3306 if (!node || !refNode)
3309 NodeImpl *parent = refNode->parentNode();
3313 int exceptionCode = 0;
3314 parent->insertBefore(node, refNode, exceptionCode);
3315 ASSERT(exceptionCode == 0);
3319 bool isProbablyBlock(const NodeImpl *node)
3324 switch (node->id()) {
3350 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
3351 : CompositeEditCommand(document),
3352 m_fragment(fragment),
3353 m_selectReplacement(selectReplacement),
3354 m_smartReplace(smartReplace)
3358 ReplaceSelectionCommand::~ReplaceSelectionCommand()
3362 void ReplaceSelectionCommand::doApply()
3364 Selection selection = endingSelection();
3365 VisiblePosition visibleStart(selection.start());
3366 VisiblePosition visibleEnd(selection.end());
3367 bool startAtStartOfLine = isFirstVisiblePositionOnLine(visibleStart);
3368 bool startAtStartOfBlock = isFirstVisiblePositionInBlock(visibleStart);
3369 bool startAtEndOfBlock = isLastVisiblePositionInBlock(visibleStart);
3370 bool startAtBlockBoundary = startAtStartOfBlock || startAtEndOfBlock;
3371 NodeImpl *startBlock = selection.start().node()->enclosingBlockFlowElement();
3372 NodeImpl *endBlock = selection.end().node()->enclosingBlockFlowElement();
3374 bool mergeStart = false;
3375 bool mergeEnd = false;
3376 if (startBlock == endBlock && startAtStartOfBlock && startAtEndOfBlock) {
3377 // Merge start only if insertion point is in an empty block.
3381 mergeStart = !(startAtStartOfLine && (m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()));
3382 mergeEnd = !m_fragment.hasInterchangeNewline() && m_fragment.hasMoreThanOneBlock();
3385 Position startPos = Position(selection.start().node()->enclosingBlockFlowElement(), 0);
3387 EStayInBlock upstreamStayInBlock = StayInBlock;
3389 // Delete the current selection, or collapse whitespace, as needed
3390 if (selection.isRange()) {
3391 deleteSelection(false, !(m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()));
3393 else if (selection.isCaret() && mergeEnd && !startAtBlockBoundary) {
3394 // The start and the end need to wind up in separate blocks.
3395 // Insert a paragraph separator to make that happen.
3396 insertParagraphSeparator();
3397 upstreamStayInBlock = DoNotStayInBlock;
3400 selection = endingSelection();
3401 if (startAtStartOfBlock && startBlock->inDocument())
3402 startPos = Position(startBlock, 0);
3403 else if (startAtEndOfBlock)
3404 startPos = selection.start().downstream(StayInBlock);
3406 startPos = selection.start().upstream(upstreamStayInBlock);
3407 endPos = selection.end().downstream();
3409 // This command does not use any typing style that is set as a residual effect of
3411 // FIXME: Improve typing style.
3412 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3413 KHTMLPart *part = document()->part();
3414 part->clearTypingStyle();
3417 if (!m_fragment.firstChild())
3420 // Now that we are about to add content, check to see if a placeholder element
3422 NodeImpl *block = startPos.node()->enclosingBlockFlowElement();
3423 if (removeBlockPlaceholderIfNeeded(block)) {
3424 Position pos = Position(block, 0);
3425 if (!endPos.node()->inDocument()) // endPos might have been in the placeholder just removed.
3430 bool addLeadingSpace = false;
3431 bool addTrailingSpace = false;
3432 if (m_smartReplace) {
3433 addLeadingSpace = startPos.leadingWhitespacePosition().isNotNull();
3434 if (addLeadingSpace) {
3435 QChar previousChar = VisiblePosition(startPos).previous().character();
3436 if (!previousChar.isNull()) {
3437 addLeadingSpace = !part->isCharacterSmartReplaceExempt(previousChar, true);
3440 addTrailingSpace = endPos.trailingWhitespacePosition().isNotNull();
3441 if (addTrailingSpace) {
3442 QChar thisChar = VisiblePosition(endPos).character();
3443 if (!thisChar.isNull()) {
3444 addTrailingSpace = !part->isCharacterSmartReplaceExempt(thisChar, false);
3449 document()->updateLayout();
3451 NodeImpl *refBlock = startPos.node()->enclosingBlockFlowElement();
3452 Position insertionPos = startPos;
3453 bool insertBlocksBefore = true;
3455 NodeImpl *firstNodeInserted = 0;
3456 NodeImpl *lastNodeInserted = 0;
3457 bool lastNodeInsertedInMergeEnd = false;
3459 // prune empty nodes from fragment
3460 m_fragment.pruneEmptyNodes();
3462 // Merge content into the end block, if necessary.
3464 NodeImpl *node = m_fragment.mergeEndNode();
3466 NodeImpl *refNode = node;
3467 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3468 insertNodeAt(refNode, endPos.node(), endPos.offset());
3469 firstNodeInserted = refNode;
3470 lastNodeInserted = refNode;
3471 while (node && !isProbablyBlock(node)) {
3472 NodeImpl *next = node->nextSibling();
3473 insertNodeAfter(node, refNode);
3474 lastNodeInserted = node;
3478 lastNodeInsertedInMergeEnd = true;
3482 // prune empty nodes from fragment
3483 m_fragment.pruneEmptyNodes();
3485 // Merge content into the start block, if necessary.
3487 NodeImpl *node = m_fragment.mergeStartNode();
3488 NodeImpl *insertionNode = 0;
3490 NodeImpl *refNode = node;
3491 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3492 insertNodeAt(refNode, startPos.node(), startPos.offset());
3493 firstNodeInserted = refNode;
3494 if (!lastNodeInsertedInMergeEnd)
3495 lastNodeInserted = refNode;
3496 insertionNode = refNode;
3497 while (node && !isProbablyBlock(node)) {
3498 NodeImpl *next = node->nextSibling();
3499 insertNodeAfter(node, refNode);
3500 if (!lastNodeInsertedInMergeEnd)
3501 lastNodeInserted = node;
3502 insertionNode = node;
3508 insertionPos = Position(insertionNode, insertionNode->caretMaxOffset());
3509 insertBlocksBefore = false;
3512 // prune empty nodes from fragment
3513 m_fragment.pruneEmptyNodes();