2 * Copyright (C) 2004 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "htmlediting.h"
28 #include "css_computedstyle.h"
29 #include "css_value.h"
30 #include "css_valueimpl.h"
31 #include "cssproperties.h"
33 #include "dom_docimpl.h"
34 #include "dom_docimpl.h"
35 #include "dom_elementimpl.h"
36 #include "dom_nodeimpl.h"
37 #include "dom_position.h"
38 #include "dom_positioniterator.h"
39 #include "dom_stringimpl.h"
40 #include "dom_textimpl.h"
41 #include "dom2_rangeimpl.h"
42 #include "html_elementimpl.h"
43 #include "html_imageimpl.h"
44 #include "html_interchange.h"
45 #include "htmlattrs.h"
47 #include "khtml_part.h"
48 #include "khtml_part.h"
49 #include "khtmlview.h"
51 #include "render_object.h"
52 #include "render_style.h"
53 #include "render_text.h"
54 #include "visible_position.h"
55 #include "visible_units.h"
58 using DOM::CSSComputedStyleDeclarationImpl;
59 using DOM::CSSMutableStyleDeclarationImpl;
60 using DOM::CSSPrimitiveValue;
61 using DOM::CSSPrimitiveValueImpl;
62 using DOM::CSSProperty;
63 using DOM::CSSStyleDeclarationImpl;
64 using DOM::CSSValueImpl;
65 using DOM::DocumentFragmentImpl;
66 using DOM::DocumentImpl;
68 using DOM::DOMStringImpl;
69 using DOM::DoNotStayInBlock;
70 using DOM::DoNotUpdateLayout;
71 using DOM::EditingTextImpl;
72 using DOM::ElementImpl;
73 using DOM::EStayInBlock;
74 using DOM::HTMLElementImpl;
75 using DOM::HTMLImageElementImpl;
76 using DOM::NamedAttrMapImpl;
79 using DOM::NodeListImpl;
81 using DOM::PositionIterator;
84 using DOM::StayInBlock;
86 using DOM::TreeWalkerImpl;
89 #include "KWQAssertions.h"
90 #include "KWQLogging.h"
91 #include "KWQKHTMLPart.h"
95 #define ASSERT(assertion) ((void)0)
96 #define ASSERT_WITH_MESSAGE(assertion, formatAndArgs...) ((void)0)
97 #define ASSERT_NOT_REACHED() ((void)0)
98 #define LOG(channel, formatAndArgs...) ((void)0)
99 #define ERROR(formatAndArgs...) ((void)0)
100 #define ASSERT(assertion) assert(assertion)
102 #define debugPosition(a,b) ((void)0)
103 #define debugNode(a,b) ((void)0)
107 #define IF_IMPL_NULL_RETURN_ARG(arg) do { \
108 if (isNull()) { return arg; } \
111 #define IF_IMPL_NULL_RETURN do { \
112 if (isNull()) { return; } \
117 static inline bool isNBSP(const QChar &c)
119 return c == QChar(0xa0);
122 static inline bool isWS(const QChar &c)
124 return c.isSpace() && c != QChar(0xa0);
127 static inline bool isWS(const DOMString &text)
129 if (text.length() != 1)
132 return isWS(text[0]);
135 static inline bool isWS(const Position &pos)
140 if (!pos.node()->isTextNode())
143 const DOMString &string = static_cast<TextImpl *>(pos.node())->data();
144 return isWS(string[pos.offset()]);
147 static const int spacesPerTab = 4;
149 static inline bool isTab(const DOMString &text)
151 static QChar tabCharacter = QChar(0x9);
152 if (text.length() != 1)
155 return text[0] == tabCharacter;
158 static inline bool isTableStructureNode(const NodeImpl *node)
160 RenderObject *r = node->renderer();
161 return (r && (r->isTableCell() || r->isTableRow() || r->isTableSection() || r->isTableCol()));
164 static DOMString &nonBreakingSpaceString()
166 static DOMString nonBreakingSpaceString = QString(QChar(0xa0));
167 return nonBreakingSpaceString;
170 static DOMString &styleSpanClassString()
172 static DOMString styleSpanClassString = "khtml-style-span";
173 return styleSpanClassString;
176 static DOMString &blockPlaceholderClassString()
178 static DOMString blockPlaceholderClassString = "khtml-block-placeholder";
179 return blockPlaceholderClassString;
182 static void derefNodesInList(QPtrList<NodeImpl> &list)
184 for (QPtrListIterator<NodeImpl> it(list); it.current(); ++it)
185 it.current()->deref();
188 static void debugPosition(const char *prefix, const Position &pos)
193 LOG(Editing, "%s <null>", prefix);
195 LOG(Editing, "%s%s %p : %d", prefix, getTagName(pos.node()->id()).string().latin1(), pos.node(), pos.offset());
198 static void debugNode(const char *prefix, const NodeImpl *node)
203 LOG(Editing, "%s <null>", prefix);
205 LOG(Editing, "%s%s %p", prefix, getTagName(node->id()).string().latin1(), node);
208 //------------------------------------------------------------------------------------------
211 EditCommandPtr::EditCommandPtr()
215 EditCommandPtr::EditCommandPtr(EditCommand *impl) : SharedPtr<EditCommand>(impl)
219 EditCommandPtr::EditCommandPtr(const EditCommandPtr &o) : SharedPtr<EditCommand>(o)
223 EditCommandPtr::~EditCommandPtr()
227 EditCommandPtr &EditCommandPtr::operator=(const EditCommandPtr &c)
229 static_cast<SharedPtr<EditCommand> &>(*this) = c;
233 bool EditCommandPtr::isCompositeStep() const
235 IF_IMPL_NULL_RETURN_ARG(false);
236 return get()->isCompositeStep();
239 bool EditCommandPtr::isInsertTextCommand() const
241 IF_IMPL_NULL_RETURN_ARG(false);
242 return get()->isInsertTextCommand();
245 bool EditCommandPtr::isTypingCommand() const
247 IF_IMPL_NULL_RETURN_ARG(false);
248 return get()->isTypingCommand();
251 void EditCommandPtr::apply() const
257 void EditCommandPtr::unapply() const
263 void EditCommandPtr::reapply() const
269 DocumentImpl * const EditCommandPtr::document() const
271 IF_IMPL_NULL_RETURN_ARG(0);
272 return get()->document();
275 Selection EditCommandPtr::startingSelection() const
277 IF_IMPL_NULL_RETURN_ARG(Selection());
278 return get()->startingSelection();
281 Selection EditCommandPtr::endingSelection() const
283 IF_IMPL_NULL_RETURN_ARG(Selection());
284 return get()->endingSelection();
287 void EditCommandPtr::setStartingSelection(const Selection &s) const
290 get()->setStartingSelection(s);
293 void EditCommandPtr::setEndingSelection(const Selection &s) const
296 get()->setEndingSelection(s);
299 CSSMutableStyleDeclarationImpl *EditCommandPtr::typingStyle() const
301 IF_IMPL_NULL_RETURN_ARG(0);
302 return get()->typingStyle();
305 void EditCommandPtr::setTypingStyle(CSSMutableStyleDeclarationImpl *style) const
308 get()->setTypingStyle(style);
311 EditCommandPtr EditCommandPtr::parent() const
313 IF_IMPL_NULL_RETURN_ARG(0);
314 return get()->parent();
317 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
320 get()->setParent(cmd.get());
323 EditCommandPtr &EditCommandPtr::emptyCommand()
325 static EditCommandPtr m_emptyCommand;
326 return m_emptyCommand;
329 //------------------------------------------------------------------------------------------
332 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, ELegacyHTMLStyles usesLegacyStyles)
333 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
335 init(style, Position());
338 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
339 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
341 init(style, position);
344 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
347 CSSMutableStyleDeclarationImpl *mutableStyle = style->makeMutable();
351 QString styleText("");
353 QValueListConstIterator<CSSProperty> end;
354 for (QValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
355 const CSSProperty *property = &*it;
357 // If position is empty or the position passed in already has the
358 // style, just move on.
359 if (position.isNotNull() && currentlyHasStyle(position, property))
362 // If needed, figure out if this change is a legacy HTML style change.
363 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
367 styleText += property->cssText().string();
370 mutableStyle->deref();
372 // Save the result for later
373 m_cssStyle = styleText.stripWhiteSpace();
376 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
378 DOMString valueText(property->value()->cssText());
379 switch (property->id()) {
380 case CSS_PROP_FONT_WEIGHT:
381 if (strcasecmp(valueText, "bold") == 0) {
386 case CSS_PROP_FONT_STYLE:
387 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
388 m_applyItalic = true;
396 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
398 ASSERT(pos.isNotNull());
399 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
402 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
407 bool result = strcasecmp(value->cssText(), property->value()->cssText()) == 0;
412 //------------------------------------------------------------------------------------------
415 EditCommand::EditCommand(DocumentImpl *document)
416 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
419 ASSERT(m_document->part());
421 m_startingSelection = m_document->part()->selection();
422 m_endingSelection = m_startingSelection;
424 m_document->part()->setSelection(Selection(), false, true);
427 EditCommand::~EditCommand()
432 m_typingStyle->deref();
435 void EditCommand::apply()
438 ASSERT(m_document->part());
439 ASSERT(state() == NotApplied);
441 KHTMLPart *part = m_document->part();
443 ASSERT(part->selection().isNone());
449 // FIXME: Improve typing style.
450 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
451 if (!preservesTypingStyle())
454 if (!isCompositeStep()) {
455 document()->updateLayout();
456 EditCommandPtr cmd(this);
457 part->appliedEditing(cmd);
461 void EditCommand::unapply()
464 ASSERT(m_document->part());
465 ASSERT(state() == Applied);
467 bool topLevel = !isCompositeStep();
469 KHTMLPart *part = m_document->part();
472 part->setSelection(Selection(), false, true);
474 ASSERT(part->selection().isNone());
478 m_state = NotApplied;
481 document()->updateLayout();
482 EditCommandPtr cmd(this);
483 part->unappliedEditing(cmd);
487 void EditCommand::reapply()
490 ASSERT(m_document->part());
491 ASSERT(state() == NotApplied);
493 bool topLevel = !isCompositeStep();
495 KHTMLPart *part = m_document->part();
498 part->setSelection(Selection(), false, true);
500 ASSERT(part->selection().isNone());
507 document()->updateLayout();
508 EditCommandPtr cmd(this);
509 part->reappliedEditing(cmd);
513 void EditCommand::doReapply()
518 void EditCommand::setStartingSelection(const Selection &s)
520 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
521 cmd->m_startingSelection = s;
524 void EditCommand::setEndingSelection(const Selection &s)
526 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
527 cmd->m_endingSelection = s;
530 void EditCommand::assignTypingStyle(CSSMutableStyleDeclarationImpl *style)
532 if (m_typingStyle == style)
535 CSSMutableStyleDeclarationImpl *old = m_typingStyle;
536 m_typingStyle = style;
538 m_typingStyle->ref();
543 void EditCommand::setTypingStyle(CSSMutableStyleDeclarationImpl *style)
545 // FIXME: Improve typing style.
546 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
547 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
548 cmd->assignTypingStyle(style);
551 bool EditCommand::preservesTypingStyle() const
556 bool EditCommand::isInsertTextCommand() const
561 bool EditCommand::isTypingCommand() const
566 //------------------------------------------------------------------------------------------
567 // CompositeEditCommand
569 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
570 : EditCommand(document)
574 void CompositeEditCommand::doUnapply()
576 if (m_cmds.count() == 0) {
580 for (int i = m_cmds.count() - 1; i >= 0; --i)
581 m_cmds[i]->unapply();
583 setState(NotApplied);
586 void CompositeEditCommand::doReapply()
588 if (m_cmds.count() == 0) {
592 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
599 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
601 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
603 cmd.setStartingSelection(endingSelection());
604 cmd.setEndingSelection(endingSelection());
610 void CompositeEditCommand::insertParagraphSeparator()
612 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
613 applyCommandToComposite(cmd);
616 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
618 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
619 applyCommandToComposite(cmd);
622 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
624 if (refChild->parentNode()->lastChild() == refChild) {
625 appendNode(insertChild, refChild->parentNode());
628 ASSERT(refChild->nextSibling());
629 insertNodeBefore(insertChild, refChild->nextSibling());
633 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
635 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
636 NodeImpl *child = refChild->firstChild();
637 for (long i = 0; child && i < offset; i++)
638 child = child->nextSibling();
640 insertNodeBefore(insertChild, child);
642 appendNode(insertChild, refChild);
644 else if (refChild->caretMinOffset() >= offset) {
645 insertNodeBefore(insertChild, refChild);
647 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
648 splitTextNode(static_cast<TextImpl *>(refChild), offset);
649 insertNodeBefore(insertChild, refChild);
652 insertNodeAfter(insertChild, refChild);
656 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
658 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
659 applyCommandToComposite(cmd);
662 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
664 if (isTableStructureNode(node)) {
665 // Do not remove an element of table structure; remove its contents.
666 NodeImpl *child = node->firstChild();
668 NodeImpl *remove = child;
669 child = child->nextSibling();
670 removeFullySelectedNode(remove);
674 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
675 applyCommandToComposite(cmd);
679 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
681 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
682 applyCommandToComposite(cmd);
685 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
687 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
688 applyCommandToComposite(cmd);
691 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
693 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
694 applyCommandToComposite(cmd);
697 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
699 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
700 applyCommandToComposite(cmd);
703 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
705 InsertTextCommand *impl = new InsertTextCommand(document());
706 EditCommandPtr cmd(impl);
707 applyCommandToComposite(cmd);
708 impl->input(text, selectInsertedText);
711 void CompositeEditCommand::insertTextIntoNode(TextImpl *node, long offset, const DOMString &text)
713 EditCommandPtr cmd(new InsertIntoTextNode(document(), node, offset, text));
714 applyCommandToComposite(cmd);
717 void CompositeEditCommand::deleteTextFromNode(TextImpl *node, long offset, long count)
719 EditCommandPtr cmd(new DeleteFromTextNodeCommand(document(), node, offset, count));
720 applyCommandToComposite(cmd);
723 void CompositeEditCommand::replaceTextInNode(TextImpl *node, long offset, long count, const DOMString &replacementText)
725 EditCommandPtr deleteCommand(new DeleteFromTextNodeCommand(document(), node, offset, count));
726 applyCommandToComposite(deleteCommand);
727 EditCommandPtr insertCommand(new InsertIntoTextNode(document(), node, offset, replacementText));
728 applyCommandToComposite(insertCommand);
731 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
733 if (endingSelection().isRange()) {
734 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
735 applyCommandToComposite(cmd);
739 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
741 if (selection.isRange()) {
742 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
743 applyCommandToComposite(cmd);
747 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
749 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
750 applyCommandToComposite(cmd);
753 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
755 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
756 applyCommandToComposite(cmd);
759 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
761 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
762 applyCommandToComposite(cmd);
765 void CompositeEditCommand::rebalanceWhitespace()
767 Selection selection = endingSelection();
768 if (selection.isCaretOrRange()) {
769 EditCommandPtr startCmd(new RebalanceWhitespaceCommand(document(), endingSelection().start()));
770 applyCommandToComposite(startCmd);
771 if (selection.isRange()) {
772 EditCommandPtr endCmd(new RebalanceWhitespaceCommand(document(), endingSelection().end()));
773 applyCommandToComposite(endCmd);
778 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
780 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
781 // and ApplyStyleCommand::computeStyleChange.
782 // Both function do similar work, and the common parts could be factored out.
784 // FIXME: Improve typing style.
785 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
787 // update document layout once before running the rest of the function
788 // so that we avoid the expense of updating before each and every call
789 // to check a computed style
790 document()->updateLayout();
792 StyleChange styleChange(document()->part()->typingStyle());
794 NodeImpl *childToAppend = child;
795 int exceptionCode = 0;
797 if (styleChange.applyItalic()) {
798 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
799 ASSERT(exceptionCode == 0);
800 italicElement->appendChild(childToAppend, exceptionCode);
801 ASSERT(exceptionCode == 0);
802 childToAppend = italicElement;
805 if (styleChange.applyBold()) {
806 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
807 ASSERT(exceptionCode == 0);
808 boldElement->appendChild(childToAppend, exceptionCode);
809 ASSERT(exceptionCode == 0);
810 childToAppend = boldElement;
813 if (styleChange.cssStyle().length() > 0) {
814 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
815 ASSERT(exceptionCode == 0);
816 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
817 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
818 styleElement->appendChild(childToAppend, exceptionCode);
819 ASSERT(exceptionCode == 0);
820 childToAppend = styleElement;
823 return childToAppend;
826 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
828 if (!textNode || !textNode->renderer() || start >= end)
831 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
832 InlineTextBox *box = textRenderer->firstTextBox();
834 // whole text node is empty
835 removeNode(textNode);
839 long length = textNode->length();
840 if (start >= length || end > length)
844 InlineTextBox *prevBox = 0;
845 DOMStringImpl *str = 0;
847 // This loop structure works to process all gaps preceding a box,
848 // and also will look at the gap after the last box.
849 while (prevBox || box) {
850 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
852 // No more chance for any intersections
855 int gapEnd = box ? box->m_start : length;
856 bool indicesIntersect = start <= gapEnd && end >= gapStart;
857 int gapLen = gapEnd - gapStart;
858 if (indicesIntersect && gapLen > 0) {
859 gapStart = kMax(gapStart, start);
860 gapEnd = kMin(gapEnd, end);
862 str = textNode->string()->substring(start, end - start);
865 // remove text in the gap
866 str->remove(gapStart - start - removed, gapLen);
872 box = box->nextTextBox();
876 // Replace the text between start and end with our pruned version.
878 replaceTextInNode(textNode, start, end - start, str);
881 // Assert that we are not going to delete all of the text in the node.
882 // If we were, that should have been done above with the call to
883 // removeNode and return.
884 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
885 deleteTextFromNode(textNode, start, end - start);
891 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
893 if (start.isNull() || end.isNull())
896 if (RangeImpl::compareBoundaryPoints(start, end) >= 0)
899 NodeImpl *node = start.node();
901 NodeImpl *next = node->traverseNextNode();
903 if (node->isTextNode()) {
904 TextImpl *textNode = static_cast<TextImpl *>(node);
905 bool isStartNode = node == start.node();
906 bool isEndNode = node == end.node();
907 int startOffset = isStartNode ? start.offset() : 0;
908 int endOffset = isEndNode ? end.offset() : textNode->length();
909 deleteInsignificantText(textNode, startOffset, endOffset);
912 if (node == end.node())
918 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
920 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
921 deleteInsignificantText(pos, end);
924 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
926 document()->updateLayout();
928 RenderObject *renderer = node->renderer();
929 if (!renderer->isBlockFlow())
932 if (renderer->height() > 0)
935 int exceptionCode = 0;
936 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
937 ASSERT(exceptionCode == 0);
938 breakNode->setAttribute(ATTR_CLASS, blockPlaceholderClassString());
939 appendNode(breakNode, node);
942 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
944 document()->updateLayout();
946 RenderObject *renderer = node->renderer();
947 if (!renderer->isBlockFlow())
950 // This code will remove a block placeholder if it still is at the end
951 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
952 // Of course, a person who hand-edits an HTML file could move a
953 // placeholder around, but it seems OK to be unconcerned about that case.
954 NodeImpl *last = node->lastChild();
955 if (last && last->isHTMLElement()) {
956 ElementImpl *element = static_cast<ElementImpl *>(last);
957 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
965 //==========================================================================================
967 //------------------------------------------------------------------------------------------
970 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
971 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
973 ASSERT(m_appendChild);
974 m_appendChild->ref();
976 ASSERT(m_parentNode);
980 AppendNodeCommand::~AppendNodeCommand()
982 ASSERT(m_appendChild);
983 m_appendChild->deref();
985 ASSERT(m_parentNode);
986 m_parentNode->deref();
989 void AppendNodeCommand::doApply()
991 ASSERT(m_appendChild);
992 ASSERT(m_parentNode);
994 int exceptionCode = 0;
995 m_parentNode->appendChild(m_appendChild, exceptionCode);
996 ASSERT(exceptionCode == 0);
999 void AppendNodeCommand::doUnapply()
1001 ASSERT(m_appendChild);
1002 ASSERT(m_parentNode);
1003 ASSERT(state() == Applied);
1005 int exceptionCode = 0;
1006 m_parentNode->removeChild(m_appendChild, exceptionCode);
1007 ASSERT(exceptionCode == 0);
1010 //------------------------------------------------------------------------------------------
1011 // ApplyStyleCommand
1013 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style)
1014 : CompositeEditCommand(document), m_style(style->makeMutable())
1020 ApplyStyleCommand::~ApplyStyleCommand()
1026 void ApplyStyleCommand::doApply()
1028 // apply the block-centric properties of the style
1029 CSSMutableStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
1031 applyBlockStyle(blockStyle);
1033 // apply any remaining styles to the inline elements
1034 // NOTE: hopefully, this string comparison is the same as checking for a non-null diff
1035 if (blockStyle->length() < m_style->length()) {
1036 CSSMutableStyleDeclarationImpl *inlineStyle = m_style->copy();
1038 blockStyle->diff(inlineStyle);
1039 applyInlineStyle(inlineStyle);
1040 inlineStyle->deref();
1043 blockStyle->deref();
1045 setEndingSelectionNeedsLayout();
1048 void ApplyStyleCommand::applyBlockStyle(CSSMutableStyleDeclarationImpl *style)
1050 // update document layout once before removing styles
1051 // so that we avoid the expense of updating before each and every call
1052 // to check a computed style
1053 document()->updateLayout();
1055 // get positions we want to use for applying style
1056 Position start(endingSelection().start());
1057 Position end(endingSelection().end());
1059 // remove current values, if any, of the specified styles from the blocks
1060 // NOTE: tracks the previous block to avoid repeated processing
1061 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1062 NodeImpl *prevBlock = 0;
1063 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1064 NodeImpl *block = node->enclosingBlockFlowElement();
1065 if (block != prevBlock && block->isHTMLElement()) {
1066 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1071 // apply specified styles to the block flow elements in the selected range
1073 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1074 NodeImpl *block = node->enclosingBlockFlowElement();
1075 if (block != prevBlock && block->isHTMLElement()) {
1076 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1082 void ApplyStyleCommand::applyInlineStyle(CSSMutableStyleDeclarationImpl *style)
1084 // adjust to the positions we want to use for applying style
1085 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1086 Position end(endingSelection().end().upstream(StayInBlock));
1088 // update document layout once before removing styles
1089 // so that we avoid the expense of updating before each and every call
1090 // to check a computed style
1091 document()->updateLayout();
1093 // Remove style from the selection.
1094 // Use the upstream position of the start for removing style.
1095 // This will ensure we remove all traces of the relevant styles from the selection
1096 // and prevent us from adding redundant ones, as described in:
1097 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1098 removeInlineStyle(style, start.upstream(), end);
1100 // split the start node if the selection starts inside of it
1101 bool splitStart = splitTextAtStartIfNeeded(start, end);
1103 start = endingSelection().start();
1104 end = endingSelection().end();
1107 // split the end node if the selection ends inside of it
1108 splitTextAtEndIfNeeded(start, end);
1109 start = endingSelection().start();
1110 end = endingSelection().end();
1112 // update document layout once before running the rest of the function
1113 // so that we avoid the expense of updating before each and every call
1114 // to check a computed style
1115 document()->updateLayout();
1117 if (start.node() == end.node()) {
1118 // simple case...start and end are the same node
1119 addInlineStyleIfNeeded(style, start.node(), end.node());
1122 NodeImpl *node = start.node();
1124 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1125 NodeImpl *runStart = node;
1127 NodeImpl *next = node->traverseNextNode();
1128 // Break if node is the end node, or if the next node does not fit in with
1129 // the current group.
1130 if (node == end.node() ||
1131 runStart->parentNode() != next->parentNode() ||
1132 (next->isHTMLElement() && next->id() != ID_BR) ||
1133 (next->renderer() && !next->renderer()->isInline()))
1137 // Now apply style to the run we found.
1138 addInlineStyleIfNeeded(style, runStart, node);
1140 if (node == end.node())
1142 node = node->traverseNextNode();
1147 //------------------------------------------------------------------------------------------
1148 // ApplyStyleCommand: style-removal helpers
1150 bool ApplyStyleCommand::isHTMLStyleNode(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1152 QValueListConstIterator<CSSProperty> end;
1153 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1154 switch ((*it).id()) {
1155 case CSS_PROP_FONT_WEIGHT:
1156 if (elem->id() == ID_B)
1159 case CSS_PROP_FONT_STYLE:
1160 if (elem->id() == ID_I)
1169 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1171 // This node can be removed.
1172 // EDIT FIXME: This does not handle the case where the node
1173 // has attributes. But how often do people add attributes to <B> tags?
1174 // Not so often I think.
1176 removeNodePreservingChildren(elem);
1179 void ApplyStyleCommand::removeCSSStyle(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1184 CSSMutableStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1188 QValueListConstIterator<CSSProperty> end;
1189 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1190 int propertyID = (*it).id();
1191 CSSValueImpl *value = decl->getPropertyCSSValue(propertyID);
1194 removeCSSProperty(decl, propertyID);
1199 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1200 // Check to see if the span is one we added to apply style.
1201 // If it is, and there are no more attributes on the span other than our
1202 // class marker, remove the span.
1203 if (decl->length() == 0) {
1204 removeNodeAttribute(elem, ATTR_STYLE);
1205 NamedAttrMapImpl *map = elem->attributes();
1206 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1207 removeNodePreservingChildren(elem);
1212 void ApplyStyleCommand::removeBlockStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1214 ASSERT(start.isNotNull());
1215 ASSERT(end.isNotNull());
1216 ASSERT(start.node()->inDocument());
1217 ASSERT(end.node()->inDocument());
1218 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1222 void ApplyStyleCommand::removeInlineStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1224 ASSERT(start.isNotNull());
1225 ASSERT(end.isNotNull());
1226 ASSERT(start.node()->inDocument());
1227 ASSERT(end.node()->inDocument());
1228 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1230 NodeImpl *node = start.node();
1232 NodeImpl *next = node->traverseNextNode();
1233 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1234 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1235 if (isHTMLStyleNode(style, elem))
1236 removeHTMLStyleNode(elem);
1238 removeCSSStyle(style, elem);
1240 if (node == end.node())
1246 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1250 Position pos = Position(node, node->childNodeCount()).upstream();
1251 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1252 RangeImpl::compareBoundaryPoints(pos, end) <= 0;
1255 //------------------------------------------------------------------------------------------
1256 // ApplyStyleCommand: style-application helpers
1259 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1261 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1262 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1263 TextImpl *text = static_cast<TextImpl *>(start.node());
1264 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1265 applyCommandToComposite(cmd);
1266 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1272 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1274 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1275 TextImpl *text = static_cast<TextImpl *>(end.node());
1276 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1277 EditCommandPtr cmd(impl);
1278 applyCommandToComposite(cmd);
1279 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1281 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1282 return impl->node()->previousSibling();
1287 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1293 NodeImpl *node = startNode;
1295 NodeImpl *next = node->traverseNextNode();
1296 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1298 appendNode(node, element);
1300 if (node == endNode)
1306 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *block)
1308 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1310 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1311 if (styleChange.cssStyle().length() > 0) {
1312 DOMString cssText = styleChange.cssStyle();
1313 CSSMutableStyleDeclarationImpl *decl = block->inlineStyleDecl();
1315 cssText += decl->cssText();
1316 block->setAttribute(ATTR_STYLE, cssText);
1320 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1322 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1323 // Both functions do similar work, and the common parts could be factored out.
1325 StyleChange styleChange(style, Position(startNode, 0));
1326 int exceptionCode = 0;
1328 if (styleChange.cssStyle().length() > 0) {
1329 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1330 ASSERT(exceptionCode == 0);
1331 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1332 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1333 insertNodeBefore(styleElement, startNode);
1334 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1337 if (styleChange.applyBold()) {
1338 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1339 ASSERT(exceptionCode == 0);
1340 insertNodeBefore(boldElement, startNode);
1341 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1344 if (styleChange.applyItalic()) {
1345 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1346 ASSERT(exceptionCode == 0);
1347 insertNodeBefore(italicElement, startNode);
1348 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1352 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1354 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1355 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1356 EditCommandPtr split(impl);
1358 pos = Position(impl->node(), 0);
1362 // EDIT FIXME: If modified to work with the internals of applying style,
1363 // this code can work to optimize cases where a style change is taking place on
1364 // a boundary between nodes where one of the nodes has the desired style. In other
1365 // words, it is possible for content to be merged into existing nodes rather than adding
1366 // additional markup.
1367 if (currentlyHasStyle(pos))
1371 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1372 NodeImpl *nextNode = pos.node()->traverseNextNode();
1374 Position next = Position(nextNode, 0);
1375 if (currentlyHasStyle(next))
1380 // try previous node
1381 if (pos.offset() <= pos.node()->caretMinOffset()) {
1382 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1384 Position prev = Position(prevNode, prevNode->maxOffset());
1385 if (currentlyHasStyle(prev))
1394 //------------------------------------------------------------------------------------------
1395 // DeleteFromTextNodeCommand
1397 DeleteFromTextNodeCommand::DeleteFromTextNodeCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1398 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1401 ASSERT(m_offset >= 0);
1402 ASSERT(m_offset < (long)m_node->length());
1403 ASSERT(m_count >= 0);
1408 DeleteFromTextNodeCommand::~DeleteFromTextNodeCommand()
1414 void DeleteFromTextNodeCommand::doApply()
1418 int exceptionCode = 0;
1419 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1420 ASSERT(exceptionCode == 0);
1422 m_node->deleteData(m_offset, m_count, exceptionCode);
1423 ASSERT(exceptionCode == 0);
1426 void DeleteFromTextNodeCommand::doUnapply()
1429 ASSERT(!m_text.isEmpty());
1431 int exceptionCode = 0;
1432 m_node->insertData(m_offset, m_text, exceptionCode);
1433 ASSERT(exceptionCode == 0);
1436 //------------------------------------------------------------------------------------------
1437 // DeleteSelectionCommand
1439 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1440 : CompositeEditCommand(document),
1441 m_hasSelectionToDelete(false),
1442 m_smartDelete(smartDelete),
1443 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1451 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1452 : CompositeEditCommand(document),
1453 m_hasSelectionToDelete(true),
1454 m_smartDelete(smartDelete),
1455 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1456 m_selectionToDelete(selection),
1464 void DeleteSelectionCommand::initializePositionData()
1467 // Handle setting some basic positions
1469 Position start = m_selectionToDelete.start();
1470 Position end = m_selectionToDelete.end();
1472 m_upstreamStart = start.upstream(StayInBlock);
1473 m_downstreamStart = start.downstream(StayInBlock);
1474 m_upstreamEnd = end.upstream(StayInBlock);
1475 m_downstreamEnd = end.downstream(StayInBlock);
1478 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
1480 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1481 bool hasLeadingWhitespaceBeforeAdjustment = m_leadingWhitespace.isNotNull();
1482 if (m_smartDelete && hasLeadingWhitespaceBeforeAdjustment) {
1483 Position pos = VisiblePosition(start).previous().deepEquivalent();
1484 // Expand out one character upstream for smart delete and recalculate
1485 // positions based on this change.
1486 m_upstreamStart = pos.upstream(StayInBlock);
1487 m_downstreamStart = pos.downstream(StayInBlock);
1488 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1490 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1491 // Note: trailing whitespace is only considered for smart delete if there is no leading
1492 // whitespace, as in the case where you double-click the first word of a paragraph.
1493 if (m_smartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_trailingWhitespace.isNotNull()) {
1494 // Expand out one character downstream for smart delete and recalculate
1495 // positions based on this change.
1496 Position pos = VisiblePosition(end).next().deepEquivalent();
1497 m_upstreamEnd = pos.upstream(StayInBlock);
1498 m_downstreamEnd = pos.downstream(StayInBlock);
1499 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1501 m_trailingWhitespaceValid = true;
1504 // Handle setting start and end blocks and the start node.
1506 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1507 m_startBlock->ref();
1508 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1510 m_startNode = m_upstreamStart.node();
1514 // Handle detecting if the line containing the selection end is itself fully selected.
1515 // This is one of the tests that determines if block merging of content needs to be done.
1517 VisiblePosition visibleEnd(end);
1518 if (isFirstVisiblePositionOnLine(visibleEnd)) {
1519 Position previousLineStart = previousLinePosition(visibleEnd, DOWNSTREAM, 0).deepEquivalent();
1520 if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
1521 m_mergeBlocksAfterDelete = false;
1524 debugPosition("m_upstreamStart ", m_upstreamStart);
1525 debugPosition("m_downstreamStart ", m_downstreamStart);
1526 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1527 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1528 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1529 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1530 debugNode( "m_startBlock ", m_startBlock);
1531 debugNode( "m_endBlock ", m_endBlock);
1532 debugNode( "m_startNode ", m_startNode);
1535 void DeleteSelectionCommand::saveTypingStyleState()
1537 // Figure out the typing style in effect before the delete is done.
1538 // FIXME: Improve typing style.
1539 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1540 CSSComputedStyleDeclarationImpl *computedStyle = m_selectionToDelete.start().computedStyle();
1541 computedStyle->ref();
1542 m_typingStyle = computedStyle->copyInheritableProperties();
1543 m_typingStyle->ref();
1544 computedStyle->deref();
1547 bool DeleteSelectionCommand::handleSpecialCaseAllContentDelete()
1549 Position start = m_downstreamStart;
1550 Position end = m_upstreamEnd;
1552 ElementImpl *rootElement = start.node()->rootEditableElement();
1553 Position rootStart = Position(rootElement, 0);
1554 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1555 if (start == VisiblePosition(rootStart).downstreamDeepEquivalent() && end == VisiblePosition(rootEnd).deepEquivalent()) {
1556 // Delete every child of the root editable element
1557 NodeImpl *node = rootElement->firstChild();
1559 NodeImpl *next = node->traverseNextSibling();
1568 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
1570 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1571 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1572 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1573 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1574 if (isBROnLineByItself) {
1575 removeNode(m_downstreamStart.node());
1576 m_endingPosition = m_upstreamStart;
1577 m_mergeBlocksAfterDelete = false;
1581 // Check for special-case where the selection contains only a BR right after a block ended.
1582 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1583 Position upstreamFromBR = m_downstreamEnd.upstream();
1584 Position downstreamFromStart = m_downstreamStart.downstream();
1585 bool startIsBRAfterBlock = downstreamEndIsBR && downstreamFromStart.node() == m_downstreamEnd.node() &&
1586 m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamFromBR.node()->enclosingBlockFlowElement();
1587 if (startIsBRAfterBlock) {
1588 removeNode(m_downstreamEnd.node());
1589 m_endingPosition = upstreamFromBR;
1590 m_mergeBlocksAfterDelete = false;
1594 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1595 // should not be done.
1596 if (upstreamStartIsBR && downstreamStartIsBR)
1597 m_mergeBlocksAfterDelete = false;
1602 void DeleteSelectionCommand::handleGeneralDelete()
1604 int startOffset = m_upstreamStart.offset();
1606 if (startOffset == 0 && m_startNode->isBlockFlow() && m_startBlock != m_endBlock && !m_endBlock->isAncestor(m_startBlock)) {
1607 // The block containing the start of the selection is completely selected.
1608 // Delete it all in one step right here.
1609 ASSERT(!m_downstreamEnd.node()->isAncestor(m_startNode));
1611 // shift the start node to the start of the next block.
1612 NodeImpl *old = m_startNode;
1613 m_startNode = m_startBlock->traverseNextSibling();
1618 removeFullySelectedNode(m_startBlock);
1620 else if (startOffset >= m_startNode->caretMaxOffset()) {
1621 // Move the start node to the next node in the tree since the startOffset is equal to
1622 // or beyond the start node's caretMaxOffset This means there is nothing visible to delete.
1623 // However, before moving on, delete any insignificant text that may be present in a text node.
1624 if (m_startNode->isTextNode()) {
1625 // Delete any insignificant text from this node.
1626 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1627 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1628 deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1631 // shift the start node to the next
1632 NodeImpl *old = m_startNode;
1633 m_startNode = old->traverseNextNode();
1639 if (m_startNode == m_downstreamEnd.node()) {
1640 // The selection to delete is all in one node.
1641 if (!m_startNode->renderer() ||
1642 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1644 removeFullySelectedNode(m_startNode);
1646 else if (m_downstreamEnd.offset() - startOffset > 0) {
1647 // in a text node that needs to be trimmed
1648 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1649 deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
1650 m_trailingWhitespaceValid = false;
1654 // The selection to delete spans more than one node.
1655 NodeImpl *node = m_startNode;
1657 if (startOffset > 0) {
1658 // in a text node that needs to be trimmed
1659 TextImpl *text = static_cast<TextImpl *>(node);
1660 deleteTextFromNode(text, startOffset, text->length() - startOffset);
1661 node = node->traverseNextNode();
1664 // handle deleting all nodes that are completely selected
1665 while (node && node != m_downstreamEnd.node()) {
1666 if (!m_downstreamEnd.node()->isAncestor(node)) {
1667 NodeImpl *nextNode = node->traverseNextSibling();
1668 removeFullySelectedNode(node);
1672 NodeImpl *n = node->lastChild();
1673 while (n && n->lastChild())
1675 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1676 // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
1677 removeFullySelectedNode(node);
1678 m_trailingWhitespaceValid = false;
1682 node = node->traverseNextNode();
1687 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1688 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1689 // need to delete whole node
1690 // we can get here if this is the last node in the block
1691 removeFullySelectedNode(m_downstreamEnd.node());
1692 m_trailingWhitespaceValid = false;
1695 // in a text node that needs to be trimmed
1696 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1697 if (m_downstreamEnd.offset() > 0) {
1698 deleteTextFromNode(text, 0, m_downstreamEnd.offset());
1699 m_downstreamEnd = Position(text, 0);
1700 m_trailingWhitespaceValid = false;
1707 void DeleteSelectionCommand::fixupWhitespace()
1709 document()->updateLayout();
1710 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1711 LOG(Editing, "replace leading");
1712 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1713 replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1715 else if (m_trailingWhitespace.isNotNull()) {
1716 if (m_trailingWhitespaceValid) {
1717 if (!m_trailingWhitespace.isRenderedCharacter()) {
1718 LOG(Editing, "replace trailing [valid]");
1719 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1720 replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1724 Position pos = m_endingPosition.downstream(StayInBlock);
1725 pos = Position(pos.node(), pos.offset() - 1);
1726 if (isWS(pos) && !pos.isRenderedCharacter()) {
1727 LOG(Editing, "replace trailing [invalid]");
1728 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1729 replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
1730 // need to adjust ending position since the trailing position is not valid.
1731 m_endingPosition = pos;
1737 // This function moves nodes in the block containing startNode to dstBlock, starting
1738 // from startNode and proceeding to the end of the block. Nodes in the block containing
1739 // startNode that appear in document order before startNode are not moved.
1740 // This function is an important helper for deleting selections that cross block
1742 void DeleteSelectionCommand::moveNodesAfterNode()
1744 if (!m_mergeBlocksAfterDelete)
1747 if (m_endBlock == m_startBlock)
1750 NodeImpl *startNode = m_downstreamEnd.node();
1751 NodeImpl *dstNode = m_upstreamStart.node();
1753 if (!startNode->inDocument() || !dstNode->inDocument())
1756 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1757 if (isTableStructureNode(startBlock))
1758 // Do not move content between parts of a table
1761 // Now that we are about to add content, check to see if a placeholder element
1763 removeBlockPlaceholderIfNeeded(startBlock);
1765 // Move the subtree containing node
1766 NodeImpl *node = startNode->enclosingInlineElement();
1768 // Insert after the subtree containing destNode
1769 NodeImpl *refNode = dstNode->enclosingInlineElement();
1771 // Nothing to do if start is already at the beginning of dstBlock
1772 NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
1773 if (startBlock == dstBlock->firstChild())
1777 while (node && node->isAncestor(startBlock)) {
1778 NodeImpl *moveNode = node;
1779 node = node->nextSibling();
1780 removeNode(moveNode);
1781 insertNodeAfter(moveNode, refNode);
1785 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1786 // to make the layout come out right. Consider this document:
1792 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1793 // move the contents of the div to the block containing 'One' and delete the div.
1794 // This will have the side effect of moving 'Three' on to the same line as 'One'
1795 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1796 // This may not be ideal, but it is better than nothing.
1797 document()->updateLayout();
1798 if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
1799 removeNode(startBlock);
1800 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1801 int exceptionCode = 0;
1802 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1803 ASSERT(exceptionCode == 0);
1804 insertNodeAfter(breakNode, refNode);
1809 void DeleteSelectionCommand::calculateEndingPosition()
1811 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1814 m_endingPosition = m_upstreamStart;
1815 if (m_endingPosition.node()->inDocument())
1818 m_endingPosition = m_downstreamEnd;
1819 if (m_endingPosition.node()->inDocument())
1822 m_endingPosition = Position(m_startBlock, 0);
1823 if (m_endingPosition.node()->inDocument())
1826 m_endingPosition = Position(m_endBlock, 0);
1827 if (m_endingPosition.node()->inDocument())
1830 m_endingPosition = Position(document()->documentElement(), 0);
1833 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1835 // Compute the difference between the style before the delete and the style now
1836 // after the delete has been done. Set this style on the part, so other editing
1837 // commands being composed with this one will work, and also cache it on the command,
1838 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1840 // FIXME: Improve typing style.
1841 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1842 if (m_startNode == m_endingPosition.node())
1843 document()->part()->setTypingStyle(0);
1845 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1846 endingStyle.diff(m_typingStyle);
1847 if (!m_typingStyle->length()) {
1848 m_typingStyle->deref();
1851 document()->part()->setTypingStyle(m_typingStyle);
1852 setTypingStyle(m_typingStyle);
1856 void DeleteSelectionCommand::clearTransientState()
1858 m_selectionToDelete.clear();
1859 m_upstreamStart.clear();
1860 m_downstreamStart.clear();
1861 m_upstreamEnd.clear();
1862 m_downstreamEnd.clear();
1863 m_endingPosition.clear();
1864 m_leadingWhitespace.clear();
1865 m_trailingWhitespace.clear();
1868 m_startBlock->deref();
1872 m_endBlock->deref();
1876 m_startNode->deref();
1879 if (m_typingStyle) {
1880 m_typingStyle->deref();
1885 void DeleteSelectionCommand::doApply()
1887 // If selection has not been set to a custom selection when the command was created,
1888 // use the current ending selection.
1889 if (!m_hasSelectionToDelete)
1890 m_selectionToDelete = endingSelection();
1892 if (!m_selectionToDelete.isRange())
1895 initializePositionData();
1897 if (!m_startBlock || !m_endBlock) {
1898 // Can't figure out what blocks we're in. This can happen if
1899 // the document structure is not what we are expecting, like if
1900 // the document has no body element, or if the editable block
1901 // has been changed to display: inline. Some day it might
1902 // be nice to be able to deal with this, but for now, bail.
1903 clearTransientState();
1907 // Delete any text that may hinder our ability to fixup whitespace after the detele
1908 deleteInsignificantTextDownstream(m_trailingWhitespace);
1910 saveTypingStyleState();
1912 if (!handleSpecialCaseAllContentDelete())
1913 if (!handleSpecialCaseBRDelete())
1914 handleGeneralDelete();
1916 // Do block merge if start and end of selection are in different blocks.
1917 moveNodesAfterNode();
1919 calculateEndingPosition();
1922 // If the delete emptied a block, add in a placeholder so the block does not
1923 // seem to disappear.
1924 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1925 calculateTypingStyleAfterDelete();
1926 setEndingSelection(m_endingPosition);
1927 debugPosition("endingPosition ", m_endingPosition);
1928 clearTransientState();
1929 rebalanceWhitespace();
1932 bool DeleteSelectionCommand::preservesTypingStyle() const
1937 //------------------------------------------------------------------------------------------
1938 // InsertIntoTextNode
1940 InsertIntoTextNode::InsertIntoTextNode(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
1941 : EditCommand(document), m_node(node), m_offset(offset)
1944 ASSERT(m_offset >= 0);
1945 ASSERT(!text.isEmpty());
1948 m_text = text.copy(); // make a copy to ensure that the string never changes
1951 InsertIntoTextNode::~InsertIntoTextNode()
1957 void InsertIntoTextNode::doApply()
1960 ASSERT(m_offset >= 0);
1961 ASSERT(!m_text.isEmpty());
1963 int exceptionCode = 0;
1964 m_node->insertData(m_offset, m_text, exceptionCode);
1965 ASSERT(exceptionCode == 0);
1968 void InsertIntoTextNode::doUnapply()
1971 ASSERT(m_offset >= 0);
1972 ASSERT(!m_text.isEmpty());
1974 int exceptionCode = 0;
1975 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
1976 ASSERT(exceptionCode == 0);
1979 //------------------------------------------------------------------------------------------
1980 // InsertLineBreakCommand
1982 InsertLineBreakCommand::InsertLineBreakCommand(DocumentImpl *document)
1983 : CompositeEditCommand(document)
1987 void InsertLineBreakCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
1989 // Insert the BR after the caret position. In the case the
1990 // position is a block, do an append. We don't want to insert
1991 // the BR *after* the block.
1992 Position upstream(pos.upstream(StayInBlock));
1993 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1994 if (cb == pos.node())
1995 appendNode(node, cb);
1997 insertNodeAfter(node, pos.node());
2000 void InsertLineBreakCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
2002 // Insert the BR after the caret position. In the case the
2003 // position is a block, do an append. We don't want to insert
2004 // the BR *before* the block.
2005 Position upstream(pos.upstream(StayInBlock));
2006 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2007 if (cb == pos.node())
2008 appendNode(node, cb);
2010 insertNodeBefore(node, pos.node());
2013 void InsertLineBreakCommand::doApply()
2016 Selection selection = endingSelection();
2018 int exceptionCode = 0;
2019 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
2020 ASSERT(exceptionCode == 0);
2022 NodeImpl *nodeToInsert = breakNode;
2024 // Handle the case where there is a typing style.
2025 // FIXME: Improve typing style.
2026 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2027 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2028 if (typingStyle && typingStyle->length() > 0)
2029 nodeToInsert = applyTypingStyle(breakNode);
2031 Position pos(selection.start().upstream(StayInBlock));
2032 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
2033 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
2034 bool atEndOfBlock = isLastVisiblePositionInBlock(VisiblePosition(pos));
2037 LOG(Editing, "input newline case 1");
2038 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
2039 // This makes the "real" BR we want to insert appear in the rendering without any
2040 // significant side effects (and no real worries either since you can't arrow past
2042 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
2043 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
2044 insertNodeBefore(nodeToInsert, pos.node());
2047 NodeImpl *next = pos.node()->traverseNextNode();
2048 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
2049 insertNodeAfterPosition(nodeToInsert, pos);
2050 if (hasTrailingBR) {
2051 setEndingSelection(Position(next, 0));
2053 else if (!document()->inStrictMode()) {
2054 // Insert an "extra" BR at the end of the block.
2055 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
2056 ASSERT(exceptionCode == 0);
2057 insertNodeAfter(extraBreakNode, nodeToInsert);
2058 setEndingSelection(Position(extraBreakNode, 0));
2063 LOG(Editing, "input newline case 2");
2064 // Insert node before downstream position, and place caret there as well.
2065 Position endingPosition = pos.downstream(StayInBlock);
2066 insertNodeBeforePosition(nodeToInsert, endingPosition);
2067 setEndingSelection(endingPosition);
2070 LOG(Editing, "input newline case 3");
2071 // Insert BR after this node. Place caret in the position that is downstream
2072 // of the current position, reckoned before inserting the BR in between.
2073 Position endingPosition = pos.downstream(StayInBlock);
2074 insertNodeAfterPosition(nodeToInsert, pos);
2075 setEndingSelection(endingPosition);
2078 // Split a text node
2079 LOG(Editing, "input newline case 4");
2080 ASSERT(pos.node()->isTextNode());
2083 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2084 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
2085 deleteTextFromNode(textNode, 0, pos.offset());
2086 insertNodeBefore(textBeforeNode, textNode);
2087 insertNodeBefore(nodeToInsert, textNode);
2088 Position endingPosition = Position(textNode, 0);
2090 // Handle whitespace that occurs after the split
2091 document()->updateLayout();
2092 if (!endingPosition.isRenderedCharacter()) {
2093 // Clear out all whitespace and insert one non-breaking space
2094 deleteInsignificantTextDownstream(endingPosition);
2095 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
2098 setEndingSelection(endingPosition);
2100 rebalanceWhitespace();
2103 //------------------------------------------------------------------------------------------
2104 // InsertNodeBeforeCommand
2106 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2107 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2109 ASSERT(m_insertChild);
2110 m_insertChild->ref();
2116 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2118 ASSERT(m_insertChild);
2119 m_insertChild->deref();
2122 m_refChild->deref();
2125 void InsertNodeBeforeCommand::doApply()
2127 ASSERT(m_insertChild);
2129 ASSERT(m_refChild->parentNode());
2131 int exceptionCode = 0;
2132 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2133 ASSERT(exceptionCode == 0);
2136 void InsertNodeBeforeCommand::doUnapply()
2138 ASSERT(m_insertChild);
2140 ASSERT(m_refChild->parentNode());
2142 int exceptionCode = 0;
2143 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2144 ASSERT(exceptionCode == 0);
2147 //------------------------------------------------------------------------------------------
2148 // InsertParagraphSeparatorCommand
2150 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(DocumentImpl *document)
2151 : CompositeEditCommand(document)
2155 InsertParagraphSeparatorCommand::~InsertParagraphSeparatorCommand()
2157 derefNodesInList(clonedNodes);
2160 void InsertParagraphSeparatorCommand::doApply()
2162 Selection selection = endingSelection();
2163 if (selection.isNone())
2166 // Delete the current selection.
2167 // If the selection is a range and the start and end nodes are in different blocks,
2168 // then this command bails after the delete, but takes the one additional step of
2169 // moving the selection downstream so it is in the ending block (if that block is
2170 // still around, that is).
2171 Position pos = selection.start();
2172 if (selection.isRange()) {
2173 NodeImpl *startBlockBeforeDelete = selection.start().node()->enclosingBlockFlowElement();
2174 NodeImpl *endBlockBeforeDelete = selection.end().node()->enclosingBlockFlowElement();
2175 bool doneAfterDelete = startBlockBeforeDelete != endBlockBeforeDelete;
2176 deleteSelection(false, false);
2177 if (doneAfterDelete) {
2178 document()->updateLayout();
2179 setEndingSelection(endingSelection().start().downstream());
2180 rebalanceWhitespace();
2183 pos = endingSelection().start().upstream();
2186 // Find the start block.
2187 NodeImpl *startNode = pos.node();
2188 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
2189 if (!startBlock || !startBlock->parentNode())
2192 // Build up list of ancestors in between the start node and the start block.
2193 for (NodeImpl *n = startNode->parentNode(); n && n != startBlock; n = n->parentNode())
2194 ancestors.prepend(n);
2196 // Make new block to represent the newline.
2197 // If the start block is the body, just make a P tag, otherwise, make a shallow clone
2198 // of the the start block.
2199 NodeImpl *addedBlock = 0;
2200 if (startBlock->id() == ID_BODY) {
2201 int exceptionCode = 0;
2202 addedBlock = document()->createHTMLElement("P", exceptionCode);
2203 ASSERT(exceptionCode == 0);
2204 appendNode(addedBlock, startBlock);
2207 addedBlock = startBlock->cloneNode(false);
2208 insertNodeAfter(addedBlock, startBlock);
2211 insertBlockPlaceholderIfNeeded(addedBlock);
2212 clonedNodes.append(addedBlock);
2214 if (!isLastVisiblePositionInNode(VisiblePosition(pos), startBlock)) {
2215 // Split at pos if in the middle of a text node.
2216 if (startNode->isTextNode()) {
2217 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2218 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2219 if (pos.offset() > 0 && !atEnd) {
2220 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2221 EditCommandPtr cmd(splitCommand);
2222 applyCommandToComposite(cmd);
2223 startNode = splitCommand->node();
2224 pos = Position(startNode, 0);
2227 startNode = startNode->traverseNextNode();
2231 else if (pos.offset() > 0) {
2232 startNode = startNode->traverseNextNode();
2236 // Make clones of ancestors in between the start node and the start block.
2237 NodeImpl *parent = addedBlock;
2238 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2239 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2241 clonedNodes.append(child);
2242 appendNode(child, parent);
2246 // Move the start node and the siblings of the start node.
2247 NodeImpl *n = startNode;
2248 if (n->id() == ID_BR)
2249 n = n->nextSibling();
2250 while (n && n != addedBlock) {
2251 NodeImpl *next = n->nextSibling();
2253 appendNode(n, parent);
2257 // Move everything after the start node.
2258 NodeImpl *leftParent = ancestors.last();
2259 while (leftParent && leftParent != startBlock) {
2260 parent = parent->parentNode();
2261 NodeImpl *n = leftParent->nextSibling();
2263 NodeImpl *next = n->nextSibling();
2265 appendNode(n, parent);
2268 leftParent = leftParent->parentNode();
2272 // Put the selection right at the start of the added block.
2273 setEndingSelection(Position(addedBlock, 0));
2274 rebalanceWhitespace();
2277 //------------------------------------------------------------------------------------------
2278 // InsertParagraphSeparatorInQuotedContentCommand
2280 InsertParagraphSeparatorInQuotedContentCommand::InsertParagraphSeparatorInQuotedContentCommand(DocumentImpl *document)
2281 : CompositeEditCommand(document)
2285 InsertParagraphSeparatorInQuotedContentCommand::~InsertParagraphSeparatorInQuotedContentCommand()
2287 derefNodesInList(clonedNodes);
2289 m_breakNode->deref();
2292 bool InsertParagraphSeparatorInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
2294 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
2297 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
2300 void InsertParagraphSeparatorInQuotedContentCommand::doApply()
2302 Selection selection = endingSelection();
2303 if (selection.isNone())
2306 // Delete the current selection.
2307 Position pos = selection.start();
2308 if (selection.isRange()) {
2309 deleteSelection(false, false);
2310 pos = endingSelection().start().upstream();
2313 // Find the top-most blockquote from the start.
2314 NodeImpl *startNode = pos.node();
2315 NodeImpl *topBlockquote = 0;
2316 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
2317 if (isMailBlockquote(n))
2320 if (!topBlockquote || !topBlockquote->parentNode())
2323 // Build up list of ancestors in between the start node and the top blockquote.
2324 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
2325 ancestors.prepend(n);
2327 // Insert a break after the top blockquote.
2328 int exceptionCode = 0;
2329 m_breakNode = document()->createHTMLElement("BR", exceptionCode);
2331 ASSERT(exceptionCode == 0);
2332 insertNodeAfter(m_breakNode, topBlockquote);
2334 if (!isLastVisiblePositionInNode(VisiblePosition(pos), topBlockquote)) {
2335 // Split at pos if in the middle of a text node.
2336 if (startNode->isTextNode()) {
2337 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2338 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2339 if (pos.offset() > 0 && !atEnd) {
2340 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2341 EditCommandPtr cmd(splitCommand);
2342 applyCommandToComposite(cmd);
2343 startNode = splitCommand->node();
2344 pos = Position(startNode, 0);
2347 startNode = startNode->traverseNextNode();
2351 else if (pos.offset() > 0) {
2352 startNode = startNode->traverseNextNode();
2356 // Insert a clone of the top blockquote after the break.
2357 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2358 clonedBlockquote->ref();
2359 insertBlockPlaceholderIfNeeded(clonedBlockquote);
2360 clonedNodes.append(clonedBlockquote);
2361 insertNodeAfter(clonedBlockquote, m_breakNode);
2363 // Make clones of ancestors in between the start node and the top blockquote.
2364 NodeImpl *parent = clonedBlockquote;
2365 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2366 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2368 clonedNodes.append(child);
2369 appendNode(child, parent);
2373 // Move the start node and the siblings of the start node.
2374 NodeImpl *n = startNode;
2375 bool startIsBR = n->id() == ID_BR;
2377 n = n->nextSibling();
2379 NodeImpl *next = n->nextSibling();
2381 appendNode(n, parent);
2385 // Move everything after the start node.
2386 NodeImpl *leftParent = ancestors.last();
2390 leftParent = topBlockquote;
2391 ElementImpl *b = document()->createHTMLElement("BR", exceptionCode);
2393 clonedNodes.append(b);
2394 ASSERT(exceptionCode == 0);
2395 appendNode(b, leftParent);
2398 leftParent = ancestors.last();
2399 while (leftParent && leftParent != topBlockquote) {
2400 parent = parent->parentNode();
2401 NodeImpl *n = leftParent->nextSibling();
2403 NodeImpl *next = n->nextSibling();
2405 appendNode(n, parent);
2408 leftParent = leftParent->parentNode();
2412 // Put the selection right before the break.
2413 setEndingSelection(Position(m_breakNode, 0));
2414 rebalanceWhitespace();
2417 //------------------------------------------------------------------------------------------
2418 // InsertTextCommand
2420 InsertTextCommand::InsertTextCommand(DocumentImpl *document)
2421 : CompositeEditCommand(document), m_charactersAdded(0)
2425 void InsertTextCommand::doApply()
2429 void InsertTextCommand::deleteCharacter()
2431 ASSERT(state() == Applied);
2433 Selection selection = endingSelection();
2435 if (!selection.start().node()->isTextNode())
2438 int exceptionCode = 0;
2439 int offset = selection.start().offset() - 1;
2440 if (offset >= selection.start().node()->caretMinOffset()) {
2441 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2442 textNode->deleteData(offset, 1, exceptionCode);
2443 ASSERT(exceptionCode == 0);
2444 selection = Selection(Position(textNode, offset));
2445 setEndingSelection(selection);
2446 m_charactersAdded--;
2450 Position InsertTextCommand::prepareForTextInsertion(bool adjustDownstream)
2452 // Prepare for text input by looking at the current position.
2453 // It may be necessary to insert a text node to receive characters.
2454 Selection selection = endingSelection();
2455 ASSERT(selection.isCaret());
2457 Position pos = selection.start();
2458 if (adjustDownstream)
2459 pos = pos.downstream(StayInBlock);
2461 pos = pos.upstream(StayInBlock);
2463 if (!pos.node()->isTextNode()) {
2464 NodeImpl *textNode = document()->createEditingTextNode("");
2465 NodeImpl *nodeToInsert = textNode;
2467 // Handle the case where there is a typing style.
2468 // FIXME: Improve typing style.
2469 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2470 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2471 if (typingStyle && typingStyle->length() > 0)
2472 nodeToInsert = applyTypingStyle(textNode);
2474 // Now insert the node in the right place
2475 if (pos.node()->isEditableBlock()) {
2476 LOG(Editing, "prepareForTextInsertion case 1");
2477 appendNode(nodeToInsert, pos.node());
2479 else if (pos.node()->caretMinOffset() == pos.offset()) {
2480 LOG(Editing, "prepareForTextInsertion case 2");
2481 insertNodeBefore(nodeToInsert, pos.node());
2483 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2484 LOG(Editing, "prepareForTextInsertion case 3");
2485 insertNodeAfter(nodeToInsert, pos.node());
2488 ASSERT_NOT_REACHED();
2490 pos = Position(textNode, 0);
2493 // Handle the case where there is a typing style.
2494 // FIXME: Improve typing style.
2495 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2496 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2497 if (typingStyle && typingStyle->length() > 0) {
2498 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2499 // Need to split current text node in order to insert a span.
2500 TextImpl *text = static_cast<TextImpl *>(pos.node());
2501 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2502 EditCommandPtr cmd(impl);
2503 applyCommandToComposite(cmd);
2504 setEndingSelection(Position(impl->node(), 0));
2507 TextImpl *editingTextNode = document()->createEditingTextNode("");
2508 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2509 if (node->isBlockFlow())
2510 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2512 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2513 pos = Position(editingTextNode, 0);
2519 void InsertTextCommand::input(const DOMString &text, bool selectInsertedText)
2521 Selection selection = endingSelection();
2522 bool adjustDownstream = isFirstVisiblePositionOnLine(VisiblePosition(selection.start().downstream(StayInBlock)));
2524 // Delete the current selection, or collapse whitespace, as needed
2525 if (selection.isRange())
2528 // Delete any insignificant text that could get in the way of whitespace turning
2529 // out correctly after the insertion.
2530 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2532 // Make sure the document is set up to receive text
2533 Position pos = prepareForTextInsertion(adjustDownstream);
2535 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2536 long offset = pos.offset();
2538 // Now that we are about to add content, check to see if a placeholder element
2540 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2542 // These are temporary implementations for inserting adjoining spaces
2543 // into a document. We are working on a CSS-related whitespace solution
2544 // that will replace this some day. We hope.
2546 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2547 // although the number of spaces varies (we choose four spaces).
2548 // Note that there is no attempt to make this work like a real tab stop, it is merely
2549 // a set number of spaces. This also seems to be the HTML editing convention.
2550 for (int i = 0; i < spacesPerTab; i++) {
2551 insertSpace(textNode, offset);
2552 rebalanceWhitespace();
2553 document()->updateLayout();
2555 if (selectInsertedText)
2556 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2558 setEndingSelection(Position(textNode, offset + spacesPerTab));
2559 m_charactersAdded += spacesPerTab;
2561 else if (isWS(text)) {
2562 insertSpace(textNode, offset);
2563 if (selectInsertedText)
2564 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2566 setEndingSelection(Position(textNode, offset + 1));
2567 m_charactersAdded++;
2568 rebalanceWhitespace();
2571 const DOMString &existingText = textNode->data();
2572 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2573 // DOM looks like this:
2574 // character nbsp caret
2575 // As we are about to insert a non-whitespace character at the caret
2576 // convert the nbsp to a regular space.
2577 // EDIT FIXME: This needs to be improved some day to convert back only
2578 // those nbsp's added by the editor to make rendering come out right.
2579 replaceTextInNode(textNode, offset - 1, 1, " ");
2581 insertTextIntoNode(textNode, offset, text);
2582 if (selectInsertedText)
2583 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2585 setEndingSelection(Position(textNode, offset + text.length()));
2586 m_charactersAdded += text.length();
2590 void InsertTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2594 DOMString text(textNode->data());
2596 // count up all spaces and newlines in front of the caret
2597 // delete all collapsed ones
2598 // this will work out OK since the offset we have been passed has been upstream-ized
2600 for (unsigned int i = offset; i < text.length(); i++) {
2607 // By checking the character at the downstream position, we can
2608 // check if there is a rendered WS at the caret
2609 Position pos(textNode, offset);
2610 Position downstream = pos.downstream();
2611 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2612 count--; // leave this WS in
2614 deleteTextFromNode(textNode, offset, count);
2617 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2618 // insert a "regular" space
2619 insertTextIntoNode(textNode, offset, " ");
2623 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2624 // DOM looks like this:
2626 // insert a space between the two nbsps
2627 insertTextIntoNode(textNode, offset - 1, " ");
2632 insertTextIntoNode(textNode, offset, nonBreakingSpaceString());
2635 bool InsertTextCommand::isInsertTextCommand() const
2640 //------------------------------------------------------------------------------------------
2641 // JoinTextNodesCommand
2643 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2644 : EditCommand(document), m_text1(text1), m_text2(text2)
2648 ASSERT(m_text1->nextSibling() == m_text2);
2649 ASSERT(m_text1->length() > 0);
2650 ASSERT(m_text2->length() > 0);
2656 JoinTextNodesCommand::~JoinTextNodesCommand()
2664 void JoinTextNodesCommand::doApply()
2668 ASSERT(m_text1->nextSibling() == m_text2);
2670 int exceptionCode = 0;
2671 m_text2->insertData(0, m_text1->data(), exceptionCode);
2672 ASSERT(exceptionCode == 0);
2674 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2675 ASSERT(exceptionCode == 0);
2677 m_offset = m_text1->length();
2680 void JoinTextNodesCommand::doUnapply()
2683 ASSERT(m_offset > 0);
2685 int exceptionCode = 0;
2687 m_text2->deleteData(0, m_offset, exceptionCode);
2688 ASSERT(exceptionCode == 0);
2690 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2691 ASSERT(exceptionCode == 0);
2693 ASSERT(m_text2->previousSibling()->isTextNode());
2694 ASSERT(m_text2->previousSibling() == m_text1);
2697 //------------------------------------------------------------------------------------------
2698 // MoveSelectionCommand
2700 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2701 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2707 MoveSelectionCommand::~MoveSelectionCommand()
2710 m_fragment->deref();
2713 void MoveSelectionCommand::doApply()
2715 Selection selection = endingSelection();
2716 ASSERT(selection.isRange());
2718 // Update the position otherwise it may become invalid after the selection is deleted.
2719 NodeImpl *positionNode = m_position.node();
2720 long positionOffset = m_position.offset();
2721 Position selectionEnd = selection.end();
2722 long selectionEndOffset = selectionEnd.offset();
2723 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2724 positionOffset -= selectionEndOffset;
2725 Position selectionStart = selection.start();
2726 if (selectionStart.node() == positionNode) {
2727 positionOffset += selectionStart.offset();
2731 deleteSelection(m_smartMove);
2733 setEndingSelection(Position(positionNode, positionOffset));
2734 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2735 applyCommandToComposite(cmd);
2738 //------------------------------------------------------------------------------------------
2739 // RebalanceWhitespaceCommand
2741 RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(DocumentImpl *document, const Position &pos)
2742 : EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset), m_downstreamOffset(InvalidOffset)
2746 RebalanceWhitespaceCommand::~RebalanceWhitespaceCommand()
2750 void RebalanceWhitespaceCommand::doApply()
2752 static DOMString space(" ");
2754 if (m_position.isNull() || !m_position.node()->isTextNode())
2757 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2758 DOMString text = textNode->data();
2759 if (text.length() == 0)
2762 // find upstream offset
2763 long upstream = m_position.offset();
2764 while (upstream > 0 && isWS(text[upstream - 1]) || isNBSP(text[upstream - 1])) {
2766 m_upstreamOffset = upstream;
2769 // find downstream offset
2770 long downstream = m_position.offset();
2771 while ((unsigned)downstream < text.length() && isWS(text[downstream]) || isNBSP(text[downstream])) {
2773 m_downstreamOffset = downstream;
2776 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2779 m_upstreamOffset = upstream;
2780 m_downstreamOffset = downstream;
2781 long length = m_downstreamOffset - m_upstreamOffset;
2783 m_beforeString = text.substring(m_upstreamOffset, length);
2785 // The following loop figures out a "rebalanced" whitespace string for any length
2786 // string, and takes into account the special cases that need to handled for the
2787 // start and end of strings (i.e. first and last character must be an nbsp.
2788 long i = m_upstreamOffset;
2789 while (i < m_downstreamOffset) {
2790 long add = (m_downstreamOffset - i) % 3;
2793 m_afterString += nonBreakingSpaceString();
2794 m_afterString += space;
2795 m_afterString += nonBreakingSpaceString();
2799 if (i == 0 || (unsigned)i + 1 == text.length()) // at start or end of string
2800 m_afterString += nonBreakingSpaceString();
2802 m_afterString += space;
2805 if ((unsigned)i + 2 == text.length()) {
2807 m_afterString += nonBreakingSpaceString();
2808 m_afterString += nonBreakingSpaceString();
2811 m_afterString += nonBreakingSpaceString();
2812 m_afterString += space;
2819 text.remove(m_upstreamOffset, length);
2820 text.insert(m_afterString, m_upstreamOffset);
2823 void RebalanceWhitespaceCommand::doUnapply()
2825 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2828 ASSERT(m_position.node()->isTextNode());
2829 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2830 DOMString text = textNode->data();
2831 text.remove(m_upstreamOffset, m_afterString.length());
2832 text.insert(m_beforeString, m_upstreamOffset);
2835 bool RebalanceWhitespaceCommand::preservesTypingStyle() const
2840 //------------------------------------------------------------------------------------------
2841 // RemoveCSSPropertyCommand
2843 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2844 : EditCommand(document), m_decl(decl->makeMutable()), m_property(property), m_important(false)
2850 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
2856 void RemoveCSSPropertyCommand::doApply()
2860 m_oldValue = m_decl->getPropertyValue(m_property);
2861 ASSERT(!m_oldValue.isNull());
2863 m_important = m_decl->getPropertyPriority(m_property);
2864 m_decl->removeProperty(m_property);
2867 void RemoveCSSPropertyCommand::doUnapply()
2870 ASSERT(!m_oldValue.isNull());
2872 m_decl->setProperty(m_property, m_oldValue, m_important);
2875 //------------------------------------------------------------------------------------------
2876 // RemoveNodeAttributeCommand
2878 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
2879 : EditCommand(document), m_element(element), m_attribute(attribute)
2885 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
2891 void RemoveNodeAttributeCommand::doApply()
2895 m_oldValue = m_element->getAttribute(m_attribute);
2896 ASSERT(!m_oldValue.isNull());
2898 int exceptionCode = 0;
2899 m_element->removeAttribute(m_attribute, exceptionCode);
2900 ASSERT(exceptionCode == 0);
2903 void RemoveNodeAttributeCommand::doUnapply()
2906 ASSERT(!m_oldValue.isNull());
2908 int exceptionCode = 0;
2909 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2910 ASSERT(exceptionCode == 0);
2913 //------------------------------------------------------------------------------------------
2914 // RemoveNodeCommand
2916 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
2917 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
2919 ASSERT(m_removeChild);
2920 m_removeChild->ref();
2922 m_parent = m_removeChild->parentNode();
2926 m_refChild = m_removeChild->nextSibling();
2931 RemoveNodeCommand::~RemoveNodeCommand()
2936 ASSERT(m_removeChild);
2937 m_removeChild->deref();
2940 m_refChild->deref();
2943 void RemoveNodeCommand::doApply()
2946 ASSERT(m_removeChild);
2948 int exceptionCode = 0;
2949 m_parent->removeChild(m_removeChild, exceptionCode);
2950 ASSERT(exceptionCode == 0);
2953 void RemoveNodeCommand::doUnapply()
2956 ASSERT(m_removeChild);
2958 int exceptionCode = 0;
2959 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
2960 ASSERT(exceptionCode == 0);
2963 //------------------------------------------------------------------------------------------
2964 // RemoveNodePreservingChildrenCommand
2966 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
2967 : CompositeEditCommand(document), m_node(node)
2973 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
2979 void RemoveNodePreservingChildrenCommand::doApply()
2981 while (NodeImpl* curr = node()->firstChild()) {
2983 insertNodeBefore(curr, node());
2988 //------------------------------------------------------------------------------------------
2989 // ReplaceSelectionCommand
2991 ReplacementFragment::ReplacementFragment(DocumentFragmentImpl *fragment)
2992 : m_fragment(fragment), m_hasInterchangeNewlineComment(false), m_hasMoreThanOneBlock(false)
2995 m_type = EmptyFragment;
3001 NodeImpl *firstChild = m_fragment->firstChild();
3002 NodeImpl *lastChild = m_fragment->lastChild();
3005 m_type = EmptyFragment;
3009 if (firstChild == lastChild && firstChild->isTextNode()) {
3010 m_type = SingleTextNodeFragment;
3014 m_type = TreeFragment;
3016 NodeImpl *node = firstChild;
3017 int realBlockCount = 0;
3018 NodeImpl *commentToDelete = 0;
3020 NodeImpl *next = node->traverseNextNode();
3021 if (isInterchangeNewlineComment(node)) {
3022 m_hasInterchangeNewlineComment = true;
3023 commentToDelete = node;
3025 else if (isInterchangeConvertedSpaceSpan(node)) {
3027 while ((n = node->firstChild())) {
3030 insertNodeBefore(n, node);
3035 next = n->traverseNextNode();
3037 else if (isProbablyBlock(node))
3042 if (commentToDelete)
3043 removeNode(commentToDelete);
3045 int blockCount = realBlockCount;
3046 firstChild = m_fragment->firstChild();
3047 lastChild = m_fragment->lastChild();
3048 if (!isProbablyBlock(firstChild))
3050 if (!isProbablyBlock(lastChild) && realBlockCount > 0)
3054 m_hasMoreThanOneBlock = true;
3057 ReplacementFragment::~ReplacementFragment()
3060 m_fragment->deref();
3063 NodeImpl *ReplacementFragment::firstChild() const
3065 return m_fragment->firstChild();
3068 NodeImpl *ReplacementFragment::lastChild() const
3070 return m_fragment->lastChild();
3073 NodeImpl *ReplacementFragment::mergeStartNode() const
3075 NodeImpl *node = m_fragment->firstChild();
3077 NodeImpl *next = node->traverseNextNode();
3078 if (!isProbablyBlock(node))
3085 NodeImpl *ReplacementFragment::mergeEndNode() const
3087 NodeImpl *node = m_fragment->lastChild();
3088 while (node && node->lastChild())
3089 node = node->lastChild();
3091 NodeImpl *prev = node->traversePreviousNode();
3092 if (!isProbablyBlock(node)) {
3093 NodeImpl *previousSibling = node->previousSibling();
3095 if (!previousSibling || isProbablyBlock(previousSibling))
3097 node = previousSibling;
3098 previousSibling = node->previousSibling();
3106 void ReplacementFragment::pruneEmptyNodes()
3111 NodeImpl *node = m_fragment->firstChild();
3113 if ((node->isTextNode() && static_cast<TextImpl *>(node)->length() == 0) ||
3114 (isProbablyBlock(node) && node->childNodeCount() == 0)) {
3115 NodeImpl *next = node->traverseNextSibling();
3121 node = node->traverseNextNode();
3127 bool ReplacementFragment::isInterchangeNewlineComment(const NodeImpl *node)
3129 return isComment(node) && node->nodeValue() == KHTMLInterchangeNewline;
3132 bool ReplacementFragment::isInterchangeConvertedSpaceSpan(const NodeImpl *node)
3134 static DOMString convertedSpaceSpanClass(AppleConvertedSpace);
3135 return node->isHTMLElement() && static_cast<const HTMLElementImpl *>(node)->getAttribute(ATTR_CLASS) == convertedSpaceSpanClass;
3138 void ReplacementFragment::removeNode(NodeImpl *node)
3143 NodeImpl *parent = node->parentNode();
3147 int exceptionCode = 0;
3148 parent->removeChild(node, exceptionCode);
3149 ASSERT(exceptionCode == 0);
3152 void ReplacementFragment::insertNodeBefore(NodeImpl *node, NodeImpl *refNode)
3154 if (!node || !refNode)
3157 NodeImpl *parent = refNode->parentNode();
3161 int exceptionCode = 0;
3162 parent->insertBefore(node, refNode, exceptionCode);
3163 ASSERT(exceptionCode == 0);
3167 bool isComment(const NodeImpl *node)
3169 return node && node->nodeType() == Node::COMMENT_NODE;
3172 bool isProbablyBlock(const NodeImpl *node)
3177 switch (node->id()) {
3203 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
3204 : CompositeEditCommand(document),
3205 m_fragment(fragment),
3206 m_selectReplacement(selectReplacement),
3207 m_smartReplace(smartReplace)
3211 ReplaceSelectionCommand::~ReplaceSelectionCommand()
3215 void ReplaceSelectionCommand::doApply()
3217 Selection selection = endingSelection();
3218 VisiblePosition visibleStart(selection.start());
3219 VisiblePosition visibleEnd(selection.end());
3220 bool startAtStartOfLine = isFirstVisiblePositionOnLine(visibleStart);
3221 bool startAtStartOfBlock = isFirstVisiblePositionInBlock(visibleStart);
3222 bool startAtEndOfBlock = isLastVisiblePositionInBlock(visibleStart);
3223 bool startAtBlockBoundary = startAtStartOfBlock || startAtEndOfBlock;
3224 NodeImpl *startBlock = selection.start().node()->enclosingBlockFlowElement();
3225 NodeImpl *endBlock = selection.end().node()->enclosingBlockFlowElement();
3227 bool mergeStart = !(startAtStartOfLine && (m_fragment.hasInterchangeNewlineComment() || m_fragment.hasMoreThanOneBlock()));
3228 bool mergeEnd = !m_fragment.hasInterchangeNewlineComment() && m_fragment.hasMoreThanOneBlock();
3229 Position startPos = Position(selection.start().node()->enclosingBlockFlowElement(), 0);
3231 EStayInBlock upstreamStayInBlock = StayInBlock;
3233 // Delete the current selection, or collapse whitespace, as needed
3234 if (selection.isRange()) {
3235 deleteSelection(false, !(m_fragment.hasInterchangeNewlineComment() || m_fragment.hasMoreThanOneBlock()));
3237 else if (selection.isCaret() && mergeEnd && !startAtBlockBoundary) {
3238 // The start and the end need to wind up in separate blocks.
3239 // Insert a paragraph separator to make that happen.
3240 insertParagraphSeparator();
3241 upstreamStayInBlock = DoNotStayInBlock;
3244 selection = endingSelection();
3245 if (startAtStartOfBlock && startBlock->inDocument())
3246 startPos = Position(startBlock, 0);
3247 else if (startAtEndOfBlock)
3248 startPos = selection.start().downstream(StayInBlock);
3250 startPos = selection.start().upstream(upstreamStayInBlock);
3251 endPos = selection.end().downstream();
3253 // This command does not use any typing style that is set as a residual effect of
3255 // FIXME: Improve typing style.
3256 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3257 KHTMLPart *part = document()->part();
3258 part->clearTypingStyle();
3261 if (!m_fragment.firstChild())
3264 // Now that we are about to add content, check to see if a placeholder element
3266 NodeImpl *block = startPos.node()->enclosingBlockFlowElement();
3267 if (removeBlockPlaceholderIfNeeded(block)) {
3268 startPos = Position(block, 0);
3271 bool addLeadingSpace = false;
3272 bool addTrailingSpace = false;
3273 if (m_smartReplace) {
3274 addLeadingSpace = startPos.leadingWhitespacePosition().isNull();
3275 if (addLeadingSpace) {
3276 QChar previousChar = VisiblePosition(startPos).previous().character();
3277 if (!previousChar.isNull()) {
3278 addLeadingSpace = !part->isCharacterSmartReplaceExempt(previousChar, true);
3281 addTrailingSpace = endPos.trailingWhitespacePosition().isNull();
3282 if (addTrailingSpace) {
3283 QChar thisChar = VisiblePosition(endPos).character();
3284 if (!thisChar.isNull()) {
3285 addTrailingSpace = !part->isCharacterSmartReplaceExempt(thisChar, false);
3290 document()->updateLayout();
3292 NodeImpl *refBlock = startPos.node()->enclosingBlockFlowElement();
3293 Position insertionPos = startPos;
3294 bool insertBlocksBefore = true;
3296 NodeImpl *firstNodeInserted = 0;
3297 NodeImpl *lastNodeInserted = 0;
3298 bool lastNodeInsertedInMergeEnd = false;
3300 // prune empty nodes from fragment
3301 m_fragment.pruneEmptyNodes();
3303 // Merge content into the end block, if necessary.
3305 NodeImpl *node = m_fragment.mergeEndNode();
3307 NodeImpl *refNode = node;
3308 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3309 insertNodeAt(refNode, endPos.node(), endPos.offset());
3310 firstNodeInserted = refNode;
3311 lastNodeInserted = refNode;
3312 while (node && !isProbablyBlock(node)) {
3313 NodeImpl *next = node->nextSibling();
3314 insertNodeAfter(node, refNode);
3315 lastNodeInserted = node;
3319 lastNodeInsertedInMergeEnd = true;
3323 // prune empty nodes from fragment
3324 m_fragment.pruneEmptyNodes();
3326 // Merge content into the start block, if necessary.
3328 NodeImpl *node = m_fragment.mergeStartNode();
3329 NodeImpl *insertionNode = 0;
3331 NodeImpl *refNode = node;
3332 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3333 insertNodeAt(refNode, startPos.node(), startPos.offset());
3334 firstNodeInserted = refNode;
3335 if (!lastNodeInsertedInMergeEnd)
3336 lastNodeInserted = refNode;
3337 insertionNode = refNode;
3338 while (node && !isProbablyBlock(node)) {
3339 NodeImpl *next = node->nextSibling();
3340 insertNodeAfter(node, refNode);
3341 if (!lastNodeInsertedInMergeEnd)
3342 lastNodeInserted = node;
3343 insertionNode = node;
3349 insertionPos = Position(insertionNode, insertionNode->caretMaxOffset());
3350 insertBlocksBefore = false;
3353 // prune empty nodes from fragment
3354 m_fragment.pruneEmptyNodes();
3356 // Merge everything remaining.
3357 NodeImpl *node = m_fragment.firstChild();
3359 NodeImpl *refNode = node;
3360 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3361 if (isProbablyBlock(refNode) && (insertBlocksBefore || startAtStartOfBlock)) {
3362 insertNodeBefore(refNode, refBlock);
3364 else if (isProbablyBlock(refNode) && startAtEndOfBlock) {
3365 insertNodeAfter(refNode, refBlock);
3368 insertNodeAt(refNode, insertionPos.node(), insertionPos.offset());
3370 if (!firstNodeInserted)
3371 firstNodeInserted = refNode;
3372 if (!lastNodeInsertedInMergeEnd)
3373 lastNodeInserted = refNode;
3375 NodeImpl *next = node->nextSibling();
3376 insertNodeAfter(node, refNode);
3377 if (!lastNodeInsertedInMergeEnd)
3378 lastNodeInserted = node;
3382 document()->updateLayout();
3383 insertionPos = Position(lastNodeInserted, lastNodeInserted->caretMaxOffset());
3386 // Handle "smart replace" whitespace
3387 if (addTrailingSpace && lastNodeInserted) {
3388 if (lastNodeInserted->isTextNode()) {
3389 TextImpl *text = static_cast<TextImpl *>(lastNodeInserted);
3390 insertTextIntoNode(text, text->length(), nonBreakingSpaceString());
3391 insertionPos = Position(text, text->length());
3394 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3395 insertNodeAfter(node, lastNodeInserted);
3396 if (!firstNodeInserted)
3397 firstNodeInserted = node;
3398 lastNodeInserted = node;
3399 insertionPos = Position(node, 1);
3403 if (addLeadingSpace && firstNodeInserted) {
3404 if (firstNodeInserted->isTextNode()) {
3405 TextImpl *text = static_cast<TextImpl *>(firstNodeInserted);
3406 insertTextIntoNode(text, 0, nonBreakingSpaceString());
3409 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3410 insertNodeBefore(node, firstNodeInserted);
3411 firstNodeInserted = node;
3412 if (!lastNodeInsertedInMergeEnd)
3413 lastNodeInserted = node;
3417 // Handle trailing newline
3418 if (m_fragment.hasInterchangeNewlineComment()) {
3419 if (startBlock == endBlock && !isProbablyBlock(lastNodeInserted)) {
3420 setEndingSelection(insertionPos);
3421 insertParagraphSeparator();
3422 endPos = endingSelection().end().downstream();
3424 completeHTMLReplacement(startPos, endPos);
3427 if (lastNodeInserted->id() == ID_BR && !document()->inStrictMode()) {
3428 document()->updateLayout();
3429 VisiblePosition pos(Position(lastNodeInserted, 0));
3430 if (isLastVisiblePositionInBlock(pos)) {
3431 NodeImpl *next = lastNodeInserted->traverseNextNode();
3432 bool hasTrailingBR = next && next->id() == ID_BR && lastNodeInserted->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
3433 if (!hasTrailingBR) {
3434 // Insert an "extra" BR at the end of the block.
3435 int exceptionCode = 0;
3436 ElementImpl *extraBreakNode = document()->createHTMLElement("br", exceptionCode);
3437 ASSERT(exceptionCode == 0);
3438 insertNodeBefore(extraBreakNode, lastNodeInserted);
3442 completeHTMLReplacement(firstNodeInserted, lastNodeInserted);
3446 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &start, const Position &end)
3448 if (start.isNull() || !start.node()->inDocument() || end.isNull() || !end.node()->inDocument())
3450 m_selectReplacement ? setEndingSelection(Selection(start, end)) : setEndingSelection(end);
3451 rebalanceWhitespace();
3454 void ReplaceSelectionCommand::completeHTMLReplacement(NodeImpl *firstNodeInserted, NodeImpl *lastNodeInserted)
3456 if (!firstNodeInserted || !firstNodeInserted->inDocument() ||
3457 !lastNodeInserted || !lastNodeInserted->inDocument())
3460 // Find the last leaf.
3461 NodeImpl *lastLeaf = lastNodeInserted;
3463 NodeImpl *nextChild = lastLeaf->lastChild();
3466 lastLeaf = nextChild;
3469 // Find the first leaf.
3470 NodeImpl *firstLeaf = firstNodeInserted;
3472 NodeImpl *nextChild = firstLeaf->firstChild();
3475 firstLeaf = nextChild;
3478 Position start(firstLeaf, firstLeaf->caretMinOffset());
3479 Position end(lastLeaf, lastLeaf->caretMaxOffset());
3480 Selection replacementSelection(start, end);
3481 if (m_selectReplacement) {
3482 // Select what was inserted.
3483 setEndingSelection(replacementSelection);
3486 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
3487 setEndingSelection(end);
3489 rebalanceWhitespace();
3492 //------------------------------------------------------------------------------------------
3493 // SetNodeAttributeCommand
3495 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
3496 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
3500 ASSERT(!m_value.isNull());
3503 SetNodeAttributeCommand::~SetNodeAttributeCommand()
3509 void SetNodeAttributeCommand::doApply()