2 * Copyright (C) 2004 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "htmlediting.h"
28 #include "css_computedstyle.h"
29 #include "css_value.h"
30 #include "css_valueimpl.h"
31 #include "cssproperties.h"
33 #include "dom_docimpl.h"
34 #include "dom_docimpl.h"
35 #include "dom_elementimpl.h"
36 #include "dom_nodeimpl.h"
37 #include "dom_position.h"
38 #include "dom_positioniterator.h"
39 #include "dom_stringimpl.h"
40 #include "dom_textimpl.h"
41 #include "dom2_rangeimpl.h"
42 #include "html_elementimpl.h"
43 #include "html_imageimpl.h"
44 #include "html_interchange.h"
45 #include "htmlattrs.h"
47 #include "khtml_part.h"
48 #include "khtml_part.h"
49 #include "khtmlview.h"
51 #include "render_object.h"
52 #include "render_style.h"
53 #include "render_text.h"
54 #include "visible_position.h"
55 #include "visible_units.h"
58 using DOM::CSSComputedStyleDeclarationImpl;
59 using DOM::CSSMutableStyleDeclarationImpl;
60 using DOM::CSSPrimitiveValue;
61 using DOM::CSSPrimitiveValueImpl;
62 using DOM::CSSProperty;
63 using DOM::CSSStyleDeclarationImpl;
64 using DOM::CSSValueImpl;
65 using DOM::DocumentFragmentImpl;
66 using DOM::DocumentImpl;
68 using DOM::DOMStringImpl;
69 using DOM::DoNotStayInBlock;
70 using DOM::DoNotUpdateLayout;
71 using DOM::EditingTextImpl;
72 using DOM::ElementImpl;
73 using DOM::EStayInBlock;
74 using DOM::HTMLElementImpl;
75 using DOM::HTMLImageElementImpl;
76 using DOM::NamedAttrMapImpl;
79 using DOM::NodeListImpl;
81 using DOM::PositionIterator;
84 using DOM::StayInBlock;
86 using DOM::TreeWalkerImpl;
89 #include "KWQAssertions.h"
90 #include "KWQLogging.h"
91 #include "KWQKHTMLPart.h"
95 #define ASSERT(assertion) ((void)0)
96 #define ASSERT_WITH_MESSAGE(assertion, formatAndArgs...) ((void)0)
97 #define ASSERT_NOT_REACHED() ((void)0)
98 #define LOG(channel, formatAndArgs...) ((void)0)
99 #define ERROR(formatAndArgs...) ((void)0)
100 #define ASSERT(assertion) assert(assertion)
102 #define debugPosition(a,b) ((void)0)
103 #define debugNode(a,b) ((void)0)
107 #define IF_IMPL_NULL_RETURN_ARG(arg) do { \
108 if (isNull()) { return arg; } \
111 #define IF_IMPL_NULL_RETURN do { \
112 if (isNull()) { return; } \
117 static inline bool isNBSP(const QChar &c)
119 return c == QChar(0xa0);
122 static inline bool isWS(const QChar &c)
124 return c.isSpace() && c != QChar(0xa0);
127 static inline bool isWS(const DOMString &text)
129 if (text.length() != 1)
132 return isWS(text[0]);
135 static inline bool isWS(const Position &pos)
140 if (!pos.node()->isTextNode())
143 const DOMString &string = static_cast<TextImpl *>(pos.node())->data();
144 return isWS(string[pos.offset()]);
147 static const int spacesPerTab = 4;
149 static inline bool isTab(const DOMString &text)
151 static QChar tabCharacter = QChar(0x9);
152 if (text.length() != 1)
155 return text[0] == tabCharacter;
158 static inline bool isTableStructureNode(const NodeImpl *node)
160 RenderObject *r = node->renderer();
161 return (r && (r->isTableCell() || r->isTableRow() || r->isTableSection() || r->isTableCol()));
164 static DOMString &nonBreakingSpaceString()
166 static DOMString nonBreakingSpaceString = QString(QChar(0xa0));
167 return nonBreakingSpaceString;
170 static DOMString &styleSpanClassString()
172 static DOMString styleSpanClassString = "khtml-style-span";
173 return styleSpanClassString;
176 static DOMString &blockPlaceholderClassString()
178 static DOMString blockPlaceholderClassString = "khtml-block-placeholder";
179 return blockPlaceholderClassString;
182 static void derefNodesInList(QPtrList<NodeImpl> &list)
184 for (QPtrListIterator<NodeImpl> it(list); it.current(); ++it)
185 it.current()->deref();
188 static void debugPosition(const char *prefix, const Position &pos)
193 LOG(Editing, "%s <null>", prefix);
195 LOG(Editing, "%s%s %p : %d", prefix, pos.node()->nodeName().string().latin1(), pos.node(), pos.offset());
198 static void debugNode(const char *prefix, const NodeImpl *node)
203 LOG(Editing, "%s <null>", prefix);
205 LOG(Editing, "%s%s %p", prefix, node->nodeName().string().latin1(), node);
208 //------------------------------------------------------------------------------------------
211 EditCommandPtr::EditCommandPtr()
215 EditCommandPtr::EditCommandPtr(EditCommand *impl) : SharedPtr<EditCommand>(impl)
219 EditCommandPtr::EditCommandPtr(const EditCommandPtr &o) : SharedPtr<EditCommand>(o)
223 EditCommandPtr::~EditCommandPtr()
227 EditCommandPtr &EditCommandPtr::operator=(const EditCommandPtr &c)
229 static_cast<SharedPtr<EditCommand> &>(*this) = c;
233 bool EditCommandPtr::isCompositeStep() const
235 IF_IMPL_NULL_RETURN_ARG(false);
236 return get()->isCompositeStep();
239 bool EditCommandPtr::isInsertTextCommand() const
241 IF_IMPL_NULL_RETURN_ARG(false);
242 return get()->isInsertTextCommand();
245 bool EditCommandPtr::isTypingCommand() const
247 IF_IMPL_NULL_RETURN_ARG(false);
248 return get()->isTypingCommand();
251 void EditCommandPtr::apply() const
257 void EditCommandPtr::unapply() const
263 void EditCommandPtr::reapply() const
269 EditAction EditCommandPtr::editingAction() const
271 IF_IMPL_NULL_RETURN_ARG(EditActionUnspecified);
272 return get()->editingAction();
275 DocumentImpl * const EditCommandPtr::document() const
277 IF_IMPL_NULL_RETURN_ARG(0);
278 return get()->document();
281 Selection EditCommandPtr::startingSelection() const
283 IF_IMPL_NULL_RETURN_ARG(Selection());
284 return get()->startingSelection();
287 Selection EditCommandPtr::endingSelection() const
289 IF_IMPL_NULL_RETURN_ARG(Selection());
290 return get()->endingSelection();
293 void EditCommandPtr::setStartingSelection(const Selection &s) const
296 get()->setStartingSelection(s);
299 void EditCommandPtr::setEndingSelection(const Selection &s) const
302 get()->setEndingSelection(s);
305 CSSMutableStyleDeclarationImpl *EditCommandPtr::typingStyle() const
307 IF_IMPL_NULL_RETURN_ARG(0);
308 return get()->typingStyle();
311 void EditCommandPtr::setTypingStyle(CSSMutableStyleDeclarationImpl *style) const
314 get()->setTypingStyle(style);
317 EditCommandPtr EditCommandPtr::parent() const
319 IF_IMPL_NULL_RETURN_ARG(0);
320 return get()->parent();
323 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
326 get()->setParent(cmd.get());
329 EditCommandPtr &EditCommandPtr::emptyCommand()
331 static EditCommandPtr m_emptyCommand;
332 return m_emptyCommand;
335 //------------------------------------------------------------------------------------------
338 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, ELegacyHTMLStyles usesLegacyStyles)
339 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
341 init(style, Position());
344 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
345 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
347 init(style, position);
350 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
353 CSSMutableStyleDeclarationImpl *mutableStyle = style->makeMutable();
357 QString styleText("");
359 QValueListConstIterator<CSSProperty> end;
360 for (QValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
361 const CSSProperty *property = &*it;
363 // If position is empty or the position passed in already has the
364 // style, just move on.
365 if (position.isNotNull() && currentlyHasStyle(position, property))
368 // If needed, figure out if this change is a legacy HTML style change.
369 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
373 styleText += property->cssText().string();
376 mutableStyle->deref();
378 // Save the result for later
379 m_cssStyle = styleText.stripWhiteSpace();
382 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
384 DOMString valueText(property->value()->cssText());
385 switch (property->id()) {
386 case CSS_PROP_FONT_WEIGHT:
387 if (strcasecmp(valueText, "bold") == 0) {
392 case CSS_PROP_FONT_STYLE:
393 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
394 m_applyItalic = true;
402 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
404 ASSERT(pos.isNotNull());
405 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
408 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
413 bool result = strcasecmp(value->cssText(), property->value()->cssText()) == 0;
418 //------------------------------------------------------------------------------------------
421 EditCommand::EditCommand(DocumentImpl *document)
422 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
425 ASSERT(m_document->part());
427 m_startingSelection = m_document->part()->selection();
428 m_endingSelection = m_startingSelection;
430 m_document->part()->setSelection(Selection(), false, true);
433 EditCommand::~EditCommand()
438 m_typingStyle->deref();
441 void EditCommand::apply()
444 ASSERT(m_document->part());
445 ASSERT(state() == NotApplied);
447 KHTMLPart *part = m_document->part();
449 ASSERT(part->selection().isNone());
455 // FIXME: Improve typing style.
456 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
457 if (!preservesTypingStyle())
460 if (!isCompositeStep()) {
461 document()->updateLayout();
462 EditCommandPtr cmd(this);
463 part->appliedEditing(cmd);
467 void EditCommand::unapply()
470 ASSERT(m_document->part());
471 ASSERT(state() == Applied);
473 bool topLevel = !isCompositeStep();
475 KHTMLPart *part = m_document->part();
478 part->setSelection(Selection(), false, true);
480 ASSERT(part->selection().isNone());
484 m_state = NotApplied;
487 document()->updateLayout();
488 EditCommandPtr cmd(this);
489 part->unappliedEditing(cmd);
493 void EditCommand::reapply()
496 ASSERT(m_document->part());
497 ASSERT(state() == NotApplied);
499 bool topLevel = !isCompositeStep();
501 KHTMLPart *part = m_document->part();
504 part->setSelection(Selection(), false, true);
506 ASSERT(part->selection().isNone());
513 document()->updateLayout();
514 EditCommandPtr cmd(this);
515 part->reappliedEditing(cmd);
519 void EditCommand::doReapply()
524 EditAction EditCommand::editingAction() const
526 return EditActionUnspecified;
529 void EditCommand::setStartingSelection(const Selection &s)
531 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
532 cmd->m_startingSelection = s;
535 void EditCommand::setEndingSelection(const Selection &s)
537 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
538 cmd->m_endingSelection = s;
541 void EditCommand::assignTypingStyle(CSSMutableStyleDeclarationImpl *style)
543 if (m_typingStyle == style)
546 CSSMutableStyleDeclarationImpl *old = m_typingStyle;
547 m_typingStyle = style;
549 m_typingStyle->ref();
554 void EditCommand::setTypingStyle(CSSMutableStyleDeclarationImpl *style)
556 // FIXME: Improve typing style.
557 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
558 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent)
559 cmd->assignTypingStyle(style);
562 bool EditCommand::preservesTypingStyle() const
567 bool EditCommand::isInsertTextCommand() const
572 bool EditCommand::isTypingCommand() const
577 //------------------------------------------------------------------------------------------
578 // CompositeEditCommand
580 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
581 : EditCommand(document)
585 void CompositeEditCommand::doUnapply()
587 if (m_cmds.count() == 0) {
591 for (int i = m_cmds.count() - 1; i >= 0; --i)
592 m_cmds[i]->unapply();
594 setState(NotApplied);
597 void CompositeEditCommand::doReapply()
599 if (m_cmds.count() == 0) {
603 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
610 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
612 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
614 cmd.setStartingSelection(endingSelection());
615 cmd.setEndingSelection(endingSelection());
621 void CompositeEditCommand::insertParagraphSeparator()
623 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
624 applyCommandToComposite(cmd);
627 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
629 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
630 applyCommandToComposite(cmd);
633 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
635 if (refChild->parentNode()->lastChild() == refChild) {
636 appendNode(insertChild, refChild->parentNode());
639 ASSERT(refChild->nextSibling());
640 insertNodeBefore(insertChild, refChild->nextSibling());
644 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
646 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
647 NodeImpl *child = refChild->firstChild();
648 for (long i = 0; child && i < offset; i++)
649 child = child->nextSibling();
651 insertNodeBefore(insertChild, child);
653 appendNode(insertChild, refChild);
655 else if (refChild->caretMinOffset() >= offset) {
656 insertNodeBefore(insertChild, refChild);
658 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
659 splitTextNode(static_cast<TextImpl *>(refChild), offset);
660 insertNodeBefore(insertChild, refChild);
663 insertNodeAfter(insertChild, refChild);
667 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
669 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
670 applyCommandToComposite(cmd);
673 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
675 if (isTableStructureNode(node)) {
676 // Do not remove an element of table structure; remove its contents.
677 NodeImpl *child = node->firstChild();
679 NodeImpl *remove = child;
680 child = child->nextSibling();
681 removeFullySelectedNode(remove);
685 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
686 applyCommandToComposite(cmd);
690 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
692 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
693 applyCommandToComposite(cmd);
696 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
698 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
699 applyCommandToComposite(cmd);
702 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
704 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
705 applyCommandToComposite(cmd);
708 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
710 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
711 applyCommandToComposite(cmd);
714 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
716 InsertTextCommand *impl = new InsertTextCommand(document());
717 EditCommandPtr cmd(impl);
718 applyCommandToComposite(cmd);
719 impl->input(text, selectInsertedText);
722 void CompositeEditCommand::insertTextIntoNode(TextImpl *node, long offset, const DOMString &text)
724 EditCommandPtr cmd(new InsertIntoTextNode(document(), node, offset, text));
725 applyCommandToComposite(cmd);
728 void CompositeEditCommand::deleteTextFromNode(TextImpl *node, long offset, long count)
730 EditCommandPtr cmd(new DeleteFromTextNodeCommand(document(), node, offset, count));
731 applyCommandToComposite(cmd);
734 void CompositeEditCommand::replaceTextInNode(TextImpl *node, long offset, long count, const DOMString &replacementText)
736 EditCommandPtr deleteCommand(new DeleteFromTextNodeCommand(document(), node, offset, count));
737 applyCommandToComposite(deleteCommand);
738 EditCommandPtr insertCommand(new InsertIntoTextNode(document(), node, offset, replacementText));
739 applyCommandToComposite(insertCommand);
742 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
744 if (endingSelection().isRange()) {
745 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
746 applyCommandToComposite(cmd);
750 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
752 if (selection.isRange()) {
753 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
754 applyCommandToComposite(cmd);
758 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
760 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
761 applyCommandToComposite(cmd);
764 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
766 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
767 applyCommandToComposite(cmd);
770 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
772 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
773 applyCommandToComposite(cmd);
776 void CompositeEditCommand::rebalanceWhitespace()
778 Selection selection = endingSelection();
779 if (selection.isCaretOrRange()) {
780 EditCommandPtr startCmd(new RebalanceWhitespaceCommand(document(), endingSelection().start()));
781 applyCommandToComposite(startCmd);
782 if (selection.isRange()) {
783 EditCommandPtr endCmd(new RebalanceWhitespaceCommand(document(), endingSelection().end()));
784 applyCommandToComposite(endCmd);
789 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
791 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
792 // and ApplyStyleCommand::computeStyleChange.
793 // Both function do similar work, and the common parts could be factored out.
795 // FIXME: Improve typing style.
796 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
798 // update document layout once before running the rest of the function
799 // so that we avoid the expense of updating before each and every call
800 // to check a computed style
801 document()->updateLayout();
803 StyleChange styleChange(document()->part()->typingStyle());
805 NodeImpl *childToAppend = child;
806 int exceptionCode = 0;
808 if (styleChange.applyItalic()) {
809 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
810 ASSERT(exceptionCode == 0);
811 italicElement->appendChild(childToAppend, exceptionCode);
812 ASSERT(exceptionCode == 0);
813 childToAppend = italicElement;
816 if (styleChange.applyBold()) {
817 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
818 ASSERT(exceptionCode == 0);
819 boldElement->appendChild(childToAppend, exceptionCode);
820 ASSERT(exceptionCode == 0);
821 childToAppend = boldElement;
824 if (styleChange.cssStyle().length() > 0) {
825 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
826 ASSERT(exceptionCode == 0);
827 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
828 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
829 styleElement->appendChild(childToAppend, exceptionCode);
830 ASSERT(exceptionCode == 0);
831 childToAppend = styleElement;
834 return childToAppend;
837 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
839 if (!textNode || !textNode->renderer() || start >= end)
842 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
843 InlineTextBox *box = textRenderer->firstTextBox();
845 // whole text node is empty
846 removeNode(textNode);
850 long length = textNode->length();
851 if (start >= length || end > length)
855 InlineTextBox *prevBox = 0;
856 DOMStringImpl *str = 0;
858 // This loop structure works to process all gaps preceding a box,
859 // and also will look at the gap after the last box.
860 while (prevBox || box) {
861 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
863 // No more chance for any intersections
866 int gapEnd = box ? box->m_start : length;
867 bool indicesIntersect = start <= gapEnd && end >= gapStart;
868 int gapLen = gapEnd - gapStart;
869 if (indicesIntersect && gapLen > 0) {
870 gapStart = kMax(gapStart, start);
871 gapEnd = kMin(gapEnd, end);
873 str = textNode->string()->substring(start, end - start);
876 // remove text in the gap
877 str->remove(gapStart - start - removed, gapLen);
883 box = box->nextTextBox();
887 // Replace the text between start and end with our pruned version.
889 replaceTextInNode(textNode, start, end - start, str);
892 // Assert that we are not going to delete all of the text in the node.
893 // If we were, that should have been done above with the call to
894 // removeNode and return.
895 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
896 deleteTextFromNode(textNode, start, end - start);
902 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
904 if (start.isNull() || end.isNull())
907 if (RangeImpl::compareBoundaryPoints(start, end) >= 0)
910 NodeImpl *node = start.node();
912 NodeImpl *next = node->traverseNextNode();
914 if (node->isTextNode()) {
915 TextImpl *textNode = static_cast<TextImpl *>(node);
916 bool isStartNode = node == start.node();
917 bool isEndNode = node == end.node();
918 int startOffset = isStartNode ? start.offset() : 0;
919 int endOffset = isEndNode ? end.offset() : textNode->length();
920 deleteInsignificantText(textNode, startOffset, endOffset);
923 if (node == end.node())
929 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
931 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
932 deleteInsignificantText(pos, end);
935 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
940 document()->updateLayout();
942 RenderObject *renderer = node->renderer();
943 if (!renderer || !renderer->isBlockFlow())
946 if (renderer->height() > 0)
949 appendNode(createBlockPlaceholderElement(document()), node);
952 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
957 document()->updateLayout();
959 RenderObject *renderer = node->renderer();
960 if (!renderer || !renderer->isBlockFlow())
963 // This code will remove a block placeholder if it still is at the end
964 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
965 // Of course, a person who hand-edits an HTML file could move a
966 // placeholder around, but it seems OK to be unconcerned about that case.
967 NodeImpl *last = node->lastChild();
968 if (last && last->isHTMLElement()) {
969 ElementImpl *element = static_cast<ElementImpl *>(last);
970 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
978 //==========================================================================================
980 //------------------------------------------------------------------------------------------
983 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
984 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
986 ASSERT(m_appendChild);
987 m_appendChild->ref();
989 ASSERT(m_parentNode);
993 AppendNodeCommand::~AppendNodeCommand()
995 ASSERT(m_appendChild);
996 m_appendChild->deref();
998 ASSERT(m_parentNode);
999 m_parentNode->deref();
1002 void AppendNodeCommand::doApply()
1004 ASSERT(m_appendChild);
1005 ASSERT(m_parentNode);
1007 int exceptionCode = 0;
1008 m_parentNode->appendChild(m_appendChild, exceptionCode);
1009 ASSERT(exceptionCode == 0);
1012 void AppendNodeCommand::doUnapply()
1014 ASSERT(m_appendChild);
1015 ASSERT(m_parentNode);
1016 ASSERT(state() == Applied);
1018 int exceptionCode = 0;
1019 m_parentNode->removeChild(m_appendChild, exceptionCode);
1020 ASSERT(exceptionCode == 0);
1023 //------------------------------------------------------------------------------------------
1024 // ApplyStyleCommand
1026 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style, EditAction editingAction)
1027 : CompositeEditCommand(document), m_style(style->makeMutable()), m_editingAction(editingAction)
1033 ApplyStyleCommand::~ApplyStyleCommand()
1039 void ApplyStyleCommand::doApply()
1041 // apply the block-centric properties of the style
1042 CSSMutableStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
1044 applyBlockStyle(blockStyle);
1046 // apply any remaining styles to the inline elements
1047 // NOTE: hopefully, this string comparison is the same as checking for a non-null diff
1048 if (blockStyle->length() < m_style->length()) {
1049 CSSMutableStyleDeclarationImpl *inlineStyle = m_style->copy();
1051 blockStyle->diff(inlineStyle);
1052 applyInlineStyle(inlineStyle);
1053 inlineStyle->deref();
1056 blockStyle->deref();
1058 setEndingSelectionNeedsLayout();
1061 EditAction ApplyStyleCommand::editingAction() const
1063 return m_editingAction;
1066 void ApplyStyleCommand::applyBlockStyle(CSSMutableStyleDeclarationImpl *style)
1068 // update document layout once before removing styles
1069 // so that we avoid the expense of updating before each and every call
1070 // to check a computed style
1071 document()->updateLayout();
1073 // get positions we want to use for applying style
1074 Position start(endingSelection().start());
1075 Position end(endingSelection().end());
1077 // remove current values, if any, of the specified styles from the blocks
1078 // NOTE: tracks the previous block to avoid repeated processing
1079 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1080 NodeImpl *prevBlock = 0;
1081 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1082 NodeImpl *block = node->enclosingBlockFlowElement();
1083 if (block != prevBlock && block->isHTMLElement()) {
1084 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1089 // apply specified styles to the block flow elements in the selected range
1091 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1092 NodeImpl *block = node->enclosingBlockFlowElement();
1093 if (block != prevBlock && block->isHTMLElement()) {
1094 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1100 void ApplyStyleCommand::applyInlineStyle(CSSMutableStyleDeclarationImpl *style)
1102 // adjust to the positions we want to use for applying style
1103 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1104 Position end(endingSelection().end().upstream(StayInBlock));
1106 // update document layout once before removing styles
1107 // so that we avoid the expense of updating before each and every call
1108 // to check a computed style
1109 document()->updateLayout();
1111 // Remove style from the selection.
1112 // Use the upstream position of the start for removing style.
1113 // This will ensure we remove all traces of the relevant styles from the selection
1114 // and prevent us from adding redundant ones, as described in:
1115 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1116 removeInlineStyle(style, start.upstream(), end);
1118 // split the start node if the selection starts inside of it
1119 bool splitStart = splitTextAtStartIfNeeded(start, end);
1121 start = endingSelection().start();
1122 end = endingSelection().end();
1125 // split the end node if the selection ends inside of it
1126 splitTextAtEndIfNeeded(start, end);
1127 start = endingSelection().start();
1128 end = endingSelection().end();
1130 // update document layout once before running the rest of the function
1131 // so that we avoid the expense of updating before each and every call
1132 // to check a computed style
1133 document()->updateLayout();
1135 if (start.node() == end.node()) {
1136 // simple case...start and end are the same node
1137 addInlineStyleIfNeeded(style, start.node(), end.node());
1140 NodeImpl *node = start.node();
1142 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1143 NodeImpl *runStart = node;
1145 NodeImpl *next = node->traverseNextNode();
1146 // Break if node is the end node, or if the next node does not fit in with
1147 // the current group.
1148 if (node == end.node() ||
1149 runStart->parentNode() != next->parentNode() ||
1150 (next->isHTMLElement() && next->id() != ID_BR) ||
1151 (next->renderer() && !next->renderer()->isInline()))
1155 // Now apply style to the run we found.
1156 addInlineStyleIfNeeded(style, runStart, node);
1158 if (node == end.node())
1160 node = node->traverseNextNode();
1165 //------------------------------------------------------------------------------------------
1166 // ApplyStyleCommand: style-removal helpers
1168 bool ApplyStyleCommand::isHTMLStyleNode(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1170 QValueListConstIterator<CSSProperty> end;
1171 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1172 switch ((*it).id()) {
1173 case CSS_PROP_FONT_WEIGHT:
1174 if (elem->id() == ID_B)
1177 case CSS_PROP_FONT_STYLE:
1178 if (elem->id() == ID_I)
1187 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1189 // This node can be removed.
1190 // EDIT FIXME: This does not handle the case where the node
1191 // has attributes. But how often do people add attributes to <B> tags?
1192 // Not so often I think.
1194 removeNodePreservingChildren(elem);
1197 void ApplyStyleCommand::removeCSSStyle(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *elem)
1202 CSSMutableStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1206 QValueListConstIterator<CSSProperty> end;
1207 for (QValueListConstIterator<CSSProperty> it = style->valuesIterator(); it != end; ++it) {
1208 int propertyID = (*it).id();
1209 CSSValueImpl *value = decl->getPropertyCSSValue(propertyID);
1212 removeCSSProperty(decl, propertyID);
1217 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1218 // Check to see if the span is one we added to apply style.
1219 // If it is, and there are no more attributes on the span other than our
1220 // class marker, remove the span.
1221 if (decl->length() == 0) {
1222 removeNodeAttribute(elem, ATTR_STYLE);
1223 NamedAttrMapImpl *map = elem->attributes();
1224 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1225 removeNodePreservingChildren(elem);
1230 void ApplyStyleCommand::removeBlockStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1232 ASSERT(start.isNotNull());
1233 ASSERT(end.isNotNull());
1234 ASSERT(start.node()->inDocument());
1235 ASSERT(end.node()->inDocument());
1236 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1240 void ApplyStyleCommand::removeInlineStyle(CSSMutableStyleDeclarationImpl *style, const Position &start, const Position &end)
1242 ASSERT(start.isNotNull());
1243 ASSERT(end.isNotNull());
1244 ASSERT(start.node()->inDocument());
1245 ASSERT(end.node()->inDocument());
1246 ASSERT(RangeImpl::compareBoundaryPoints(start, end) <= 0);
1248 NodeImpl *node = start.node();
1250 NodeImpl *next = node->traverseNextNode();
1251 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1252 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1253 if (isHTMLStyleNode(style, elem))
1254 removeHTMLStyleNode(elem);
1256 removeCSSStyle(style, elem);
1258 if (node == end.node())
1264 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1268 Position pos = Position(node, node->childNodeCount()).upstream();
1269 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1270 RangeImpl::compareBoundaryPoints(pos, end) <= 0;
1273 //------------------------------------------------------------------------------------------
1274 // ApplyStyleCommand: style-application helpers
1277 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1279 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1280 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1281 TextImpl *text = static_cast<TextImpl *>(start.node());
1282 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1283 applyCommandToComposite(cmd);
1284 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1290 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1292 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1293 TextImpl *text = static_cast<TextImpl *>(end.node());
1294 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1295 EditCommandPtr cmd(impl);
1296 applyCommandToComposite(cmd);
1297 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1299 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1300 return impl->node()->previousSibling();
1305 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1311 NodeImpl *node = startNode;
1313 NodeImpl *next = node->traverseNextNode();
1314 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1316 appendNode(node, element);
1318 if (node == endNode)
1324 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, HTMLElementImpl *block)
1326 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1328 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1329 if (styleChange.cssStyle().length() > 0) {
1330 DOMString cssText = styleChange.cssStyle();
1331 CSSMutableStyleDeclarationImpl *decl = block->inlineStyleDecl();
1333 cssText += decl->cssText();
1334 block->setAttribute(ATTR_STYLE, cssText);
1338 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSMutableStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1340 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1341 // Both functions do similar work, and the common parts could be factored out.
1343 StyleChange styleChange(style, Position(startNode, 0));
1344 int exceptionCode = 0;
1346 if (styleChange.cssStyle().length() > 0) {
1347 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1348 ASSERT(exceptionCode == 0);
1349 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1350 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1351 insertNodeBefore(styleElement, startNode);
1352 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1355 if (styleChange.applyBold()) {
1356 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1357 ASSERT(exceptionCode == 0);
1358 insertNodeBefore(boldElement, startNode);
1359 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1362 if (styleChange.applyItalic()) {
1363 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1364 ASSERT(exceptionCode == 0);
1365 insertNodeBefore(italicElement, startNode);
1366 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1370 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1372 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1373 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1374 EditCommandPtr split(impl);
1376 pos = Position(impl->node(), 0);
1380 // EDIT FIXME: If modified to work with the internals of applying style,
1381 // this code can work to optimize cases where a style change is taking place on
1382 // a boundary between nodes where one of the nodes has the desired style. In other
1383 // words, it is possible for content to be merged into existing nodes rather than adding
1384 // additional markup.
1385 if (currentlyHasStyle(pos))
1389 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1390 NodeImpl *nextNode = pos.node()->traverseNextNode();
1392 Position next = Position(nextNode, 0);
1393 if (currentlyHasStyle(next))
1398 // try previous node
1399 if (pos.offset() <= pos.node()->caretMinOffset()) {
1400 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1402 Position prev = Position(prevNode, prevNode->maxOffset());
1403 if (currentlyHasStyle(prev))
1412 //------------------------------------------------------------------------------------------
1413 // DeleteFromTextNodeCommand
1415 DeleteFromTextNodeCommand::DeleteFromTextNodeCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1416 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1419 ASSERT(m_offset >= 0);
1420 ASSERT(m_offset < (long)m_node->length());
1421 ASSERT(m_count >= 0);
1426 DeleteFromTextNodeCommand::~DeleteFromTextNodeCommand()
1432 void DeleteFromTextNodeCommand::doApply()
1436 int exceptionCode = 0;
1437 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1438 ASSERT(exceptionCode == 0);
1440 m_node->deleteData(m_offset, m_count, exceptionCode);
1441 ASSERT(exceptionCode == 0);
1444 void DeleteFromTextNodeCommand::doUnapply()
1447 ASSERT(!m_text.isEmpty());
1449 int exceptionCode = 0;
1450 m_node->insertData(m_offset, m_text, exceptionCode);
1451 ASSERT(exceptionCode == 0);
1454 //------------------------------------------------------------------------------------------
1455 // DeleteSelectionCommand
1457 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1458 : CompositeEditCommand(document),
1459 m_hasSelectionToDelete(false),
1460 m_smartDelete(smartDelete),
1461 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1469 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1470 : CompositeEditCommand(document),
1471 m_hasSelectionToDelete(true),
1472 m_smartDelete(smartDelete),
1473 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1474 m_selectionToDelete(selection),
1482 void DeleteSelectionCommand::initializePositionData()
1485 // Handle setting some basic positions
1487 Position start = m_selectionToDelete.start();
1488 Position end = m_selectionToDelete.end();
1490 m_upstreamStart = start.upstream(StayInBlock);
1491 m_downstreamStart = start.downstream(StayInBlock);
1492 m_upstreamEnd = end.upstream(StayInBlock);
1493 m_downstreamEnd = end.downstream(StayInBlock);
1496 // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
1498 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1499 bool hasLeadingWhitespaceBeforeAdjustment = m_leadingWhitespace.isNotNull();
1500 if (m_smartDelete && hasLeadingWhitespaceBeforeAdjustment) {
1501 Position pos = VisiblePosition(start).previous().deepEquivalent();
1502 // Expand out one character upstream for smart delete and recalculate
1503 // positions based on this change.
1504 m_upstreamStart = pos.upstream(StayInBlock);
1505 m_downstreamStart = pos.downstream(StayInBlock);
1506 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1508 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1509 // Note: trailing whitespace is only considered for smart delete if there is no leading
1510 // whitespace, as in the case where you double-click the first word of a paragraph.
1511 if (m_smartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_trailingWhitespace.isNotNull()) {
1512 // Expand out one character downstream for smart delete and recalculate
1513 // positions based on this change.
1514 Position pos = VisiblePosition(end).next().deepEquivalent();
1515 m_upstreamEnd = pos.upstream(StayInBlock);
1516 m_downstreamEnd = pos.downstream(StayInBlock);
1517 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1519 m_trailingWhitespaceValid = true;
1522 // Handle setting start and end blocks and the start node.
1524 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1525 m_startBlock->ref();
1526 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1528 m_startNode = m_upstreamStart.node();
1532 // Handle detecting if the line containing the selection end is itself fully selected.
1533 // This is one of the tests that determines if block merging of content needs to be done.
1535 VisiblePosition visibleEnd(end);
1536 if (isFirstVisiblePositionOnLine(visibleEnd)) {
1537 Position previousLineStart = previousLinePosition(visibleEnd, DOWNSTREAM, 0).deepEquivalent();
1538 if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
1539 m_mergeBlocksAfterDelete = false;
1542 debugPosition("m_upstreamStart ", m_upstreamStart);
1543 debugPosition("m_downstreamStart ", m_downstreamStart);
1544 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1545 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1546 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1547 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1548 debugNode( "m_startBlock ", m_startBlock);
1549 debugNode( "m_endBlock ", m_endBlock);
1550 debugNode( "m_startNode ", m_startNode);
1553 void DeleteSelectionCommand::insertPlaceholderForAncestorBlockContent()
1555 // This code makes sure a line does not disappear when deleting in this case:
1556 // <p>foo</p>bar<p>baz</p>
1557 // Select "bar" and hit delete. If nothing is done, the line containing bar will disappear.
1558 // It needs to be held open by inserting a placeholder.
1560 // <rdar://problem/3928305> selecting an entire line and typing over causes new inserted text at top of document
1562 // The checks below detect the case where the selection contains content in an ancestor block
1563 // surrounded by child blocks.
1565 NodeImpl *upstreamBlock = m_upstreamStart.node()->enclosingBlockFlowElement();
1566 NodeImpl *beforeUpstreamBlock = m_upstreamStart.upstream().node()->enclosingBlockFlowElement();
1568 if (upstreamBlock != beforeUpstreamBlock && beforeUpstreamBlock->isAncestor(upstreamBlock)) {
1569 NodeImpl *downstreamBlock = m_downstreamEnd.node()->enclosingBlockFlowElement();
1570 NodeImpl *afterDownstreamBlock = m_downstreamEnd.downstream().node()->enclosingBlockFlowElement();
1572 if (afterDownstreamBlock != downstreamBlock && afterDownstreamBlock != upstreamBlock) {
1573 NodeImpl *block = createDefaultParagraphElement(document());
1574 insertNodeBefore(block, m_upstreamStart.node());
1575 insertBlockPlaceholderIfNeeded(block);
1576 m_endingPosition = Position(block, 0);
1581 void DeleteSelectionCommand::saveTypingStyleState()
1583 // Figure out the typing style in effect before the delete is done.
1584 // FIXME: Improve typing style.
1585 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1586 CSSComputedStyleDeclarationImpl *computedStyle = m_selectionToDelete.start().computedStyle();
1587 computedStyle->ref();
1588 m_typingStyle = computedStyle->copyInheritableProperties();
1589 m_typingStyle->ref();
1590 computedStyle->deref();
1593 bool DeleteSelectionCommand::handleSpecialCaseAllContentDelete()
1595 Position start = m_downstreamStart;
1596 Position end = m_upstreamEnd;
1598 ElementImpl *rootElement = start.node()->rootEditableElement();
1599 Position rootStart = Position(rootElement, 0);
1600 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1601 if (start == VisiblePosition(rootStart).downstreamDeepEquivalent() && end == VisiblePosition(rootEnd).deepEquivalent()) {
1602 // Delete every child of the root editable element
1603 NodeImpl *node = rootElement->firstChild();
1605 NodeImpl *next = node->traverseNextSibling();
1614 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
1616 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1617 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1618 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1619 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1620 if (isBROnLineByItself) {
1621 removeNode(m_downstreamStart.node());
1622 m_endingPosition = m_upstreamStart;
1623 m_mergeBlocksAfterDelete = false;
1627 // Check for special-case where the selection contains only a BR right after a block ended.
1628 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1629 Position upstreamFromBR = m_downstreamEnd.upstream();
1630 Position downstreamFromStart = m_downstreamStart.downstream();
1631 bool startIsBRAfterBlock = downstreamEndIsBR && downstreamFromStart.node() == m_downstreamEnd.node() &&
1632 m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamFromBR.node()->enclosingBlockFlowElement();
1633 if (startIsBRAfterBlock) {
1634 removeNode(m_downstreamEnd.node());
1635 m_endingPosition = upstreamFromBR;
1636 m_mergeBlocksAfterDelete = false;
1640 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1641 // should not be done.
1642 if (upstreamStartIsBR && downstreamStartIsBR)
1643 m_mergeBlocksAfterDelete = false;
1648 void DeleteSelectionCommand::handleGeneralDelete()
1650 int startOffset = m_upstreamStart.offset();
1652 if (startOffset == 0 && m_startNode->isBlockFlow() && m_startBlock != m_endBlock && !m_endBlock->isAncestor(m_startBlock)) {
1653 // The block containing the start of the selection is completely selected.
1654 // Delete it all in one step right here.
1655 ASSERT(!m_downstreamEnd.node()->isAncestor(m_startNode));
1657 // shift the start node to the start of the next block.
1658 NodeImpl *old = m_startNode;
1659 m_startNode = m_startBlock->traverseNextSibling();
1664 removeFullySelectedNode(m_startBlock);
1666 else if (startOffset >= m_startNode->caretMaxOffset()) {
1667 // Move the start node to the next node in the tree since the startOffset is equal to
1668 // or beyond the start node's caretMaxOffset This means there is nothing visible to delete.
1669 // However, before moving on, delete any insignificant text that may be present in a text node.
1670 if (m_startNode->isTextNode()) {
1671 // Delete any insignificant text from this node.
1672 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1673 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1674 deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1677 // shift the start node to the next
1678 NodeImpl *old = m_startNode;
1679 m_startNode = old->traverseNextNode();
1685 if (m_startNode == m_downstreamEnd.node()) {
1686 // The selection to delete is all in one node.
1687 if (!m_startNode->renderer() ||
1688 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1690 removeFullySelectedNode(m_startNode);
1692 else if (m_downstreamEnd.offset() - startOffset > 0) {
1693 // in a text node that needs to be trimmed
1694 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1695 deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
1696 m_trailingWhitespaceValid = false;
1700 // The selection to delete spans more than one node.
1701 NodeImpl *node = m_startNode;
1703 if (startOffset > 0) {
1704 // in a text node that needs to be trimmed
1705 TextImpl *text = static_cast<TextImpl *>(node);
1706 deleteTextFromNode(text, startOffset, text->length() - startOffset);
1707 node = node->traverseNextNode();
1710 // handle deleting all nodes that are completely selected
1711 while (node && node != m_downstreamEnd.node()) {
1712 if (!m_downstreamEnd.node()->isAncestor(node)) {
1713 NodeImpl *nextNode = node->traverseNextSibling();
1714 removeFullySelectedNode(node);
1718 NodeImpl *n = node->lastChild();
1719 while (n && n->lastChild())
1721 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1722 // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
1723 removeFullySelectedNode(node);
1724 m_trailingWhitespaceValid = false;
1728 node = node->traverseNextNode();
1733 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1734 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1735 // need to delete whole node
1736 // we can get here if this is the last node in the block
1737 removeFullySelectedNode(m_downstreamEnd.node());
1738 m_trailingWhitespaceValid = false;
1741 // in a text node that needs to be trimmed
1742 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1743 if (m_downstreamEnd.offset() > 0) {
1744 deleteTextFromNode(text, 0, m_downstreamEnd.offset());
1745 m_downstreamEnd = Position(text, 0);
1746 m_trailingWhitespaceValid = false;
1753 void DeleteSelectionCommand::fixupWhitespace()
1755 document()->updateLayout();
1756 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1757 LOG(Editing, "replace leading");
1758 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1759 replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1761 else if (m_trailingWhitespace.isNotNull()) {
1762 if (m_trailingWhitespaceValid) {
1763 if (!m_trailingWhitespace.isRenderedCharacter()) {
1764 LOG(Editing, "replace trailing [valid]");
1765 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1766 replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1770 Position pos = m_endingPosition.downstream(StayInBlock);
1771 pos = Position(pos.node(), pos.offset() - 1);
1772 if (isWS(pos) && !pos.isRenderedCharacter()) {
1773 LOG(Editing, "replace trailing [invalid]");
1774 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1775 replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
1776 // need to adjust ending position since the trailing position is not valid.
1777 m_endingPosition = pos;
1783 // This function moves nodes in the block containing startNode to dstBlock, starting
1784 // from startNode and proceeding to the end of the block. Nodes in the block containing
1785 // startNode that appear in document order before startNode are not moved.
1786 // This function is an important helper for deleting selections that cross block
1788 void DeleteSelectionCommand::moveNodesAfterNode()
1790 if (!m_mergeBlocksAfterDelete)
1793 if (m_endBlock == m_startBlock)
1796 NodeImpl *startNode = m_downstreamEnd.node();
1797 NodeImpl *dstNode = m_upstreamStart.node();
1799 if (!startNode->inDocument() || !dstNode->inDocument())
1802 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1803 if (isTableStructureNode(startBlock))
1804 // Do not move content between parts of a table
1807 // Now that we are about to add content, check to see if a placeholder element
1809 removeBlockPlaceholderIfNeeded(startBlock);
1811 // Move the subtree containing node
1812 NodeImpl *node = startNode->enclosingInlineElement();
1814 // Insert after the subtree containing destNode
1815 NodeImpl *refNode = dstNode->enclosingInlineElement();
1817 // Nothing to do if start is already at the beginning of dstBlock
1818 NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
1819 if (startBlock == dstBlock->firstChild())
1823 NodeImpl *rootNode = refNode->rootEditableElement();
1824 while (node && node->isAncestor(startBlock)) {
1825 NodeImpl *moveNode = node;
1826 node = node->nextSibling();
1827 removeNode(moveNode);
1828 if (refNode == rootNode)
1829 insertNodeAt(moveNode, refNode, 0);
1831 insertNodeAfter(moveNode, refNode);
1835 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1836 // to make the layout come out right. Consider this document:
1842 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1843 // move the contents of the div to the block containing 'One' and delete the div.
1844 // This will have the side effect of moving 'Three' on to the same line as 'One'
1845 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1846 // This may not be ideal, but it is better than nothing.
1847 document()->updateLayout();
1848 if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
1849 removeNode(startBlock);
1850 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1851 insertNodeAfter(createBreakElement(document()), refNode);
1856 void DeleteSelectionCommand::calculateEndingPosition()
1858 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1861 m_endingPosition = m_upstreamStart;
1862 if (m_endingPosition.node()->inDocument())
1865 m_endingPosition = m_downstreamEnd;
1866 if (m_endingPosition.node()->inDocument())
1869 m_endingPosition = Position(m_startBlock, 0);
1870 if (m_endingPosition.node()->inDocument())
1873 m_endingPosition = Position(m_endBlock, 0);
1874 if (m_endingPosition.node()->inDocument())
1877 m_endingPosition = Position(document()->documentElement(), 0);
1880 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1882 // Compute the difference between the style before the delete and the style now
1883 // after the delete has been done. Set this style on the part, so other editing
1884 // commands being composed with this one will work, and also cache it on the command,
1885 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1887 // FIXME: Improve typing style.
1888 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1889 if (m_startNode == m_endingPosition.node())
1890 document()->part()->setTypingStyle(0);
1892 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1893 endingStyle.diff(m_typingStyle);
1894 if (!m_typingStyle->length()) {
1895 m_typingStyle->deref();
1898 document()->part()->setTypingStyle(m_typingStyle);
1899 setTypingStyle(m_typingStyle);
1903 void DeleteSelectionCommand::clearTransientState()
1905 m_selectionToDelete.clear();
1906 m_upstreamStart.clear();
1907 m_downstreamStart.clear();
1908 m_upstreamEnd.clear();
1909 m_downstreamEnd.clear();
1910 m_endingPosition.clear();
1911 m_leadingWhitespace.clear();
1912 m_trailingWhitespace.clear();
1915 m_startBlock->deref();
1919 m_endBlock->deref();
1923 m_startNode->deref();
1926 if (m_typingStyle) {
1927 m_typingStyle->deref();
1932 void DeleteSelectionCommand::doApply()
1934 // If selection has not been set to a custom selection when the command was created,
1935 // use the current ending selection.
1936 if (!m_hasSelectionToDelete)
1937 m_selectionToDelete = endingSelection();
1939 if (!m_selectionToDelete.isRange())
1942 initializePositionData();
1944 if (!m_startBlock || !m_endBlock) {
1945 // Can't figure out what blocks we're in. This can happen if
1946 // the document structure is not what we are expecting, like if
1947 // the document has no body element, or if the editable block
1948 // has been changed to display: inline. Some day it might
1949 // be nice to be able to deal with this, but for now, bail.
1950 clearTransientState();
1954 // Delete any text that may hinder our ability to fixup whitespace after the detele
1955 deleteInsignificantTextDownstream(m_trailingWhitespace);
1957 saveTypingStyleState();
1958 insertPlaceholderForAncestorBlockContent();
1960 if (!handleSpecialCaseAllContentDelete())
1961 if (!handleSpecialCaseBRDelete())
1962 handleGeneralDelete();
1964 // Do block merge if start and end of selection are in different blocks.
1965 moveNodesAfterNode();
1967 calculateEndingPosition();
1970 // If the delete emptied a block, add in a placeholder so the block does not
1971 // seem to disappear.
1972 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1973 calculateTypingStyleAfterDelete();
1974 setEndingSelection(m_endingPosition);
1975 debugPosition("endingPosition ", m_endingPosition);
1976 clearTransientState();
1977 rebalanceWhitespace();
1980 EditAction DeleteSelectionCommand::editingAction() const
1982 // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
1983 // but in that case there's a TypingCommand that supplies the editingAction(), so
1984 // the Undo menu correctly shows "Undo Typing"
1985 return EditActionCut;
1988 bool DeleteSelectionCommand::preservesTypingStyle() const
1993 //------------------------------------------------------------------------------------------
1994 // InsertIntoTextNode
1996 InsertIntoTextNode::InsertIntoTextNode(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
1997 : EditCommand(document), m_node(node), m_offset(offset)
2000 ASSERT(m_offset >= 0);
2001 ASSERT(!text.isEmpty());
2004 m_text = text.copy(); // make a copy to ensure that the string never changes
2007 InsertIntoTextNode::~InsertIntoTextNode()
2013 void InsertIntoTextNode::doApply()
2016 ASSERT(m_offset >= 0);
2017 ASSERT(!m_text.isEmpty());
2019 int exceptionCode = 0;
2020 m_node->insertData(m_offset, m_text, exceptionCode);
2021 ASSERT(exceptionCode == 0);
2024 void InsertIntoTextNode::doUnapply()
2027 ASSERT(m_offset >= 0);
2028 ASSERT(!m_text.isEmpty());
2030 int exceptionCode = 0;
2031 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
2032 ASSERT(exceptionCode == 0);
2035 //------------------------------------------------------------------------------------------
2036 // InsertLineBreakCommand
2038 InsertLineBreakCommand::InsertLineBreakCommand(DocumentImpl *document)
2039 : CompositeEditCommand(document)
2043 bool InsertLineBreakCommand::preservesTypingStyle() const
2048 void InsertLineBreakCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
2050 // Insert the BR after the caret position. In the case the
2051 // position is a block, do an append. We don't want to insert
2052 // the BR *after* the block.
2053 Position upstream(pos.upstream(StayInBlock));
2054 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2055 if (cb == pos.node())
2056 appendNode(node, cb);
2058 insertNodeAfter(node, pos.node());
2061 void InsertLineBreakCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
2063 // Insert the BR after the caret position. In the case the
2064 // position is a block, do an append. We don't want to insert
2065 // the BR *before* the block.
2066 Position upstream(pos.upstream(StayInBlock));
2067 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
2068 if (cb == pos.node())
2069 appendNode(node, cb);
2071 insertNodeBefore(node, pos.node());
2074 void InsertLineBreakCommand::doApply()
2077 Selection selection = endingSelection();
2079 ElementImpl *breakNode = createBreakElement(document());
2080 NodeImpl *nodeToInsert = breakNode;
2082 // Handle the case where there is a typing style.
2083 // FIXME: Improve typing style.
2084 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2085 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2086 if (typingStyle && typingStyle->length() > 0)
2087 nodeToInsert = applyTypingStyle(breakNode);
2089 Position pos(selection.start().upstream(StayInBlock));
2090 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
2091 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
2092 bool atEndOfBlock = isLastVisiblePositionInBlock(VisiblePosition(pos));
2095 LOG(Editing, "input newline case 1");
2096 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
2097 // This makes the "real" BR we want to insert appear in the rendering without any
2098 // significant side effects (and no real worries either since you can't arrow past
2100 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
2101 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
2102 insertNodeBefore(nodeToInsert, pos.node());
2105 NodeImpl *next = pos.node()->traverseNextNode();
2106 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
2107 insertNodeAfterPosition(nodeToInsert, pos);
2108 if (hasTrailingBR) {
2109 setEndingSelection(Position(next, 0));
2111 else if (!document()->inStrictMode()) {
2112 // Insert an "extra" BR at the end of the block.
2113 ElementImpl *extraBreakNode = createBreakElement(document());
2114 insertNodeAfter(extraBreakNode, nodeToInsert);
2115 setEndingSelection(Position(extraBreakNode, 0));
2120 LOG(Editing, "input newline case 2");
2121 // Insert node before downstream position, and place caret there as well.
2122 Position endingPosition = pos.downstream(StayInBlock);
2123 insertNodeBeforePosition(nodeToInsert, endingPosition);
2124 setEndingSelection(endingPosition);
2127 LOG(Editing, "input newline case 3");
2128 // Insert BR after this node. Place caret in the position that is downstream
2129 // of the current position, reckoned before inserting the BR in between.
2130 Position endingPosition = pos.downstream(StayInBlock);
2131 insertNodeAfterPosition(nodeToInsert, pos);
2132 setEndingSelection(endingPosition);
2135 // Split a text node
2136 LOG(Editing, "input newline case 4");
2137 ASSERT(pos.node()->isTextNode());
2140 int exceptionCode = 0;
2141 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2142 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
2143 deleteTextFromNode(textNode, 0, pos.offset());
2144 insertNodeBefore(textBeforeNode, textNode);
2145 insertNodeBefore(nodeToInsert, textNode);
2146 Position endingPosition = Position(textNode, 0);
2148 // Handle whitespace that occurs after the split
2149 document()->updateLayout();
2150 if (!endingPosition.isRenderedCharacter()) {
2151 // Clear out all whitespace and insert one non-breaking space
2152 deleteInsignificantTextDownstream(endingPosition);
2153 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
2156 setEndingSelection(endingPosition);
2158 rebalanceWhitespace();
2161 //------------------------------------------------------------------------------------------
2162 // InsertNodeBeforeCommand
2164 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2165 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2167 ASSERT(m_insertChild);
2168 m_insertChild->ref();
2174 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2176 ASSERT(m_insertChild);
2177 m_insertChild->deref();
2180 m_refChild->deref();
2183 void InsertNodeBeforeCommand::doApply()
2185 ASSERT(m_insertChild);
2187 ASSERT(m_refChild->parentNode());
2189 int exceptionCode = 0;
2190 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2191 ASSERT(exceptionCode == 0);
2194 void InsertNodeBeforeCommand::doUnapply()
2196 ASSERT(m_insertChild);
2198 ASSERT(m_refChild->parentNode());
2200 int exceptionCode = 0;
2201 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2202 ASSERT(exceptionCode == 0);
2205 //------------------------------------------------------------------------------------------
2206 // InsertParagraphSeparatorCommand
2208 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(DocumentImpl *document)
2209 : CompositeEditCommand(document), m_fullTypingStyle(0)
2213 InsertParagraphSeparatorCommand::~InsertParagraphSeparatorCommand()
2215 derefNodesInList(clonedNodes);
2216 if (m_fullTypingStyle)
2217 m_fullTypingStyle->deref();
2220 bool InsertParagraphSeparatorCommand::preservesTypingStyle() const
2225 ElementImpl *InsertParagraphSeparatorCommand::createParagraphElement()
2227 ElementImpl *element = createDefaultParagraphElement(document());
2229 clonedNodes.append(element);
2233 void InsertParagraphSeparatorCommand::setFullTypingStyleBeforeInsertion(const Position &pos)
2235 // FIXME: Improve typing style.
2236 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2237 CSSComputedStyleDeclarationImpl *computedStyle = pos.computedStyle();
2238 computedStyle->ref();
2239 if (m_fullTypingStyle)
2240 m_fullTypingStyle->deref();
2241 m_fullTypingStyle = computedStyle->copyInheritableProperties();
2242 m_fullTypingStyle->ref();
2243 computedStyle->deref();
2246 void InsertParagraphSeparatorCommand::calculateAndSetTypingStyleAfterInsertion()
2248 // FIXME: Improve typing style.
2249 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2250 if (!m_fullTypingStyle)
2253 CSSComputedStyleDeclarationImpl endingStyle(endingSelection().start().node());
2254 endingStyle.diff(m_fullTypingStyle);
2255 if (!m_fullTypingStyle->length()) {
2256 m_fullTypingStyle->deref();
2257 m_fullTypingStyle = 0;
2259 document()->part()->setTypingStyle(m_fullTypingStyle);
2260 setTypingStyle(m_fullTypingStyle);
2263 void InsertParagraphSeparatorCommand::doApply()
2265 Selection selection = endingSelection();
2266 if (selection.isNone())
2269 // Delete the current selection.
2270 // If the selection is a range and the start and end nodes are in different blocks,
2271 // then this command bails after the delete, but takes the one additional step of
2272 // moving the selection downstream so it is in the ending block (if that block is
2273 // still around, that is).
2274 Position pos = selection.start();
2276 if (selection.isRange()) {
2277 NodeImpl *startBlockBeforeDelete = selection.start().node()->enclosingBlockFlowElement();
2278 NodeImpl *endBlockBeforeDelete = selection.end().node()->enclosingBlockFlowElement();
2279 bool doneAfterDelete = startBlockBeforeDelete != endBlockBeforeDelete;
2280 setFullTypingStyleBeforeInsertion(pos);
2281 deleteSelection(false, false);
2282 if (doneAfterDelete) {
2283 document()->updateLayout();
2284 setEndingSelection(endingSelection().start().downstream());
2285 rebalanceWhitespace();
2286 calculateAndSetTypingStyleAfterInsertion();
2289 pos = endingSelection().start();
2292 setFullTypingStyleBeforeInsertion(pos);
2294 // Find the start block.
2295 NodeImpl *startNode = pos.node();
2296 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
2297 if (!startBlock || !startBlock->parentNode())
2300 VisiblePosition visiblePos(pos);
2301 bool isFirstInBlock = isFirstVisiblePositionInBlock(visiblePos);
2302 bool isLastInBlock = isLastVisiblePositionInBlock(visiblePos);
2303 bool startBlockIsRoot = startBlock == startBlock->rootEditableElement();
2305 // This is the block that is going to be inserted.
2306 NodeImpl *blockToInsert = startBlockIsRoot ? createParagraphElement() : startBlock->cloneNode(false);
2308 //---------------------------------------------------------------------
2309 // Handle empty block case.
2310 if (isFirstInBlock && isLastInBlock) {
2311 LOG(Editing, "insert paragraph separator: empty block case");
2312 if (startBlockIsRoot) {
2313 NodeImpl *extraBlock = createParagraphElement();
2314 appendNode(extraBlock, startBlock);
2315 insertBlockPlaceholderIfNeeded(extraBlock);
2316 appendNode(blockToInsert, startBlock);
2319 insertNodeAfter(blockToInsert, startBlock);
2321 insertBlockPlaceholderIfNeeded(blockToInsert);
2322 setEndingSelection(Position(blockToInsert, 0));
2323 calculateAndSetTypingStyleAfterInsertion();
2327 //---------------------------------------------------------------------
2328 // Handle case when position is in the first visible position in its block.
2329 // and similar case where upstream position is in another block.
2330 bool upstreamInDifferentBlock = startBlock != pos.upstream(DoNotStayInBlock).node()->enclosingBlockFlowElement();
2331 if (upstreamInDifferentBlock || isFirstInBlock) {
2332 LOG(Editing, "insert paragraph separator: first in block case");
2333 pos = pos.downstream(StayInBlock);
2334 NodeImpl *refNode = isFirstInBlock && !startBlockIsRoot ? startBlock : pos.node();
2335 insertNodeBefore(blockToInsert, refNode);
2336 insertBlockPlaceholderIfNeeded(blockToInsert);
2337 setEndingSelection(pos);
2338 calculateAndSetTypingStyleAfterInsertion();
2342 //---------------------------------------------------------------------
2343 // Handle case when position is in the last visible position in its block,
2344 // and similar case where downstream position is in another block.
2345 bool downstreamInDifferentBlock = startBlock != pos.downstream(DoNotStayInBlock).node()->enclosingBlockFlowElement();
2346 if (downstreamInDifferentBlock || isLastInBlock) {
2347 LOG(Editing, "insert paragraph separator: last in block case");
2348 NodeImpl *refNode = isLastInBlock && !startBlockIsRoot ? startBlock : pos.node();
2349 insertNodeAfter(blockToInsert, refNode);
2350 insertBlockPlaceholderIfNeeded(blockToInsert);
2351 setEndingSelection(Position(blockToInsert, 0));
2352 calculateAndSetTypingStyleAfterInsertion();
2356 //---------------------------------------------------------------------
2357 // Handle the (more complicated) general case,
2359 LOG(Editing, "insert paragraph separator: general case");
2361 // Check if pos.node() is a <br>. If it is, and the document is in quirks mode,
2362 // then this <br> will collapse away when we add a block after it. Add an extra <br>.
2363 if (!document()->inStrictMode()) {
2364 Position upstreamPos = pos.upstream(StayInBlock);
2365 if (upstreamPos.node()->id() == ID_BR)
2366 insertNodeAfter(createBreakElement(document()), upstreamPos.node());
2369 // Move downstream. Typing style code will take care of carrying along the
2370 // style of the upstream position.
2371 pos = pos.downstream(StayInBlock);
2372 startNode = pos.node();
2374 // Build up list of ancestors in between the start node and the start block.
2375 if (startNode != startBlock) {
2376 for (NodeImpl *n = startNode->parentNode(); n && n != startBlock; n = n->parentNode())
2377 ancestors.prepend(n);
2380 // Split at pos if in the middle of a text node.
2381 if (startNode->isTextNode()) {
2382 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2383 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2384 if (pos.offset() > 0 && !atEnd) {
2385 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2386 EditCommandPtr cmd(splitCommand);
2387 applyCommandToComposite(cmd);
2388 startNode = splitCommand->node();
2389 pos = Position(startNode, 0);
2393 // Put the added block in the tree.
2394 if (startBlockIsRoot) {
2395 NodeImpl *lastSibling = pos.node();
2396 while (lastSibling->nextSibling())
2397 lastSibling = lastSibling->nextSibling();
2398 insertNodeAfter(blockToInsert, lastSibling);
2401 insertNodeAfter(blockToInsert, startBlock);
2404 // Make clones of ancestors in between the start node and the start block.
2405 NodeImpl *parent = blockToInsert;
2406 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2407 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2409 clonedNodes.append(child);
2410 appendNode(child, parent);
2414 // Move the start node and the siblings of the start node.
2415 if (startNode != startBlock) {
2416 NodeImpl *n = startNode;
2417 while (n && n != blockToInsert) {
2418 NodeImpl *next = n->nextSibling();
2420 appendNode(n, parent);
2425 // Move everything after the start node.
2426 NodeImpl *leftParent = ancestors.last();
2427 while (leftParent && leftParent != startBlock) {
2428 parent = parent->parentNode();
2429 NodeImpl *n = leftParent->nextSibling();
2431 NodeImpl *next = n->nextSibling();
2433 appendNode(n, parent);
2436 leftParent = leftParent->parentNode();
2439 setEndingSelection(Position(blockToInsert, 0));
2440 rebalanceWhitespace();
2441 calculateAndSetTypingStyleAfterInsertion();
2444 //------------------------------------------------------------------------------------------
2445 // InsertParagraphSeparatorInQuotedContentCommand
2447 InsertParagraphSeparatorInQuotedContentCommand::InsertParagraphSeparatorInQuotedContentCommand(DocumentImpl *document)
2448 : CompositeEditCommand(document)
2452 InsertParagraphSeparatorInQuotedContentCommand::~InsertParagraphSeparatorInQuotedContentCommand()
2454 derefNodesInList(clonedNodes);
2456 m_breakNode->deref();
2459 bool InsertParagraphSeparatorInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
2461 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
2464 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
2467 void InsertParagraphSeparatorInQuotedContentCommand::doApply()
2469 Selection selection = endingSelection();
2470 if (selection.isNone())
2473 // Delete the current selection.
2474 Position pos = selection.start();
2475 if (selection.isRange()) {
2476 deleteSelection(false, false);
2477 pos = endingSelection().start().upstream();
2480 // Find the top-most blockquote from the start.
2481 NodeImpl *startNode = pos.node();
2482 NodeImpl *topBlockquote = 0;
2483 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
2484 if (isMailBlockquote(n))
2487 if (!topBlockquote || !topBlockquote->parentNode())
2490 // Build up list of ancestors in between the start node and the top blockquote.
2491 if (startNode != topBlockquote) {
2492 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
2493 ancestors.prepend(n);
2496 // Insert a break after the top blockquote.
2497 m_breakNode = createBreakElement(document());
2499 insertNodeAfter(m_breakNode, topBlockquote);
2501 if (!isLastVisiblePositionInNode(VisiblePosition(pos), topBlockquote)) {
2502 // Split at pos if in the middle of a text node.
2503 if (startNode->isTextNode()) {
2504 TextImpl *textNode = static_cast<TextImpl *>(startNode);
2505 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
2506 if (pos.offset() > 0 && !atEnd) {
2507 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
2508 EditCommandPtr cmd(splitCommand);
2509 applyCommandToComposite(cmd);
2510 startNode = splitCommand->node();
2511 pos = Position(startNode, 0);
2514 startNode = startNode->traverseNextNode();
2518 else if (pos.offset() > 0) {
2519 startNode = startNode->traverseNextNode();
2523 // Insert a clone of the top blockquote after the break.
2524 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2525 clonedBlockquote->ref();
2526 clonedNodes.append(clonedBlockquote);
2527 insertNodeAfter(clonedBlockquote, m_breakNode);
2529 // Make clones of ancestors in between the start node and the top blockquote.
2530 NodeImpl *parent = clonedBlockquote;
2531 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2532 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2534 clonedNodes.append(child);
2535 appendNode(child, parent);
2539 // Move the start node and the siblings of the start node.
2540 bool startIsBR = false;
2541 if (startNode != topBlockquote) {
2542 NodeImpl *n = startNode;
2543 bool startIsBR = n->id() == ID_BR;
2545 n = n->nextSibling();
2547 NodeImpl *next = n->nextSibling();
2549 appendNode(n, parent);
2554 // Move everything after the start node.
2555 NodeImpl *leftParent = ancestors.last();
2559 leftParent = topBlockquote;
2560 ElementImpl *b = createBreakElement(document());
2562 clonedNodes.append(b);
2563 appendNode(b, leftParent);
2566 leftParent = ancestors.last();
2567 while (leftParent && leftParent != topBlockquote) {
2568 parent = parent->parentNode();
2569 NodeImpl *n = leftParent->nextSibling();
2571 NodeImpl *next = n->nextSibling();
2573 appendNode(n, parent);
2576 leftParent = leftParent->parentNode();
2579 // Make sure the cloned block quote renders.
2580 insertBlockPlaceholderIfNeeded(clonedBlockquote);
2583 // Put the selection right before the break.
2584 setEndingSelection(Position(m_breakNode, 0));
2585 rebalanceWhitespace();
2588 //------------------------------------------------------------------------------------------
2589 // InsertTextCommand
2591 InsertTextCommand::InsertTextCommand(DocumentImpl *document)
2592 : CompositeEditCommand(document), m_charactersAdded(0)
2596 void InsertTextCommand::doApply()
2600 void InsertTextCommand::deleteCharacter()
2602 ASSERT(state() == Applied);
2604 Selection selection = endingSelection();
2606 if (!selection.start().node()->isTextNode())
2609 int exceptionCode = 0;
2610 int offset = selection.start().offset() - 1;
2611 if (offset >= selection.start().node()->caretMinOffset()) {
2612 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2613 textNode->deleteData(offset, 1, exceptionCode);
2614 ASSERT(exceptionCode == 0);
2615 selection = Selection(Position(textNode, offset));
2616 setEndingSelection(selection);
2617 m_charactersAdded--;
2621 Position InsertTextCommand::prepareForTextInsertion(bool adjustDownstream)
2623 // Prepare for text input by looking at the current position.
2624 // It may be necessary to insert a text node to receive characters.
2625 Selection selection = endingSelection();
2626 ASSERT(selection.isCaret());
2628 Position pos = selection.start();
2629 if (adjustDownstream)
2630 pos = pos.downstream(StayInBlock);
2632 pos = pos.upstream(StayInBlock);
2634 if (!pos.node()->isTextNode()) {
2635 NodeImpl *textNode = document()->createEditingTextNode("");
2636 NodeImpl *nodeToInsert = textNode;
2638 // Handle the case where there is a typing style.
2639 // FIXME: Improve typing style.
2640 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2641 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2642 if (typingStyle && typingStyle->length() > 0)
2643 nodeToInsert = applyTypingStyle(textNode);
2645 // Now insert the node in the right place
2646 if (pos.node()->isEditableBlock()) {
2647 LOG(Editing, "prepareForTextInsertion case 1");
2648 appendNode(nodeToInsert, pos.node());
2650 else if (pos.node()->caretMinOffset() == pos.offset()) {
2651 LOG(Editing, "prepareForTextInsertion case 2");
2652 insertNodeBefore(nodeToInsert, pos.node());
2654 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2655 LOG(Editing, "prepareForTextInsertion case 3");
2656 insertNodeAfter(nodeToInsert, pos.node());
2659 ASSERT_NOT_REACHED();
2661 pos = Position(textNode, 0);
2664 // Handle the case where there is a typing style.
2665 // FIXME: Improve typing style.
2666 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2667 CSSMutableStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2668 if (typingStyle && typingStyle->length() > 0) {
2669 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2670 // Need to split current text node in order to insert a span.
2671 TextImpl *text = static_cast<TextImpl *>(pos.node());
2672 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2673 EditCommandPtr cmd(impl);
2674 applyCommandToComposite(cmd);
2675 setEndingSelection(Position(impl->node(), 0));
2678 TextImpl *editingTextNode = document()->createEditingTextNode("");
2679 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2680 if (node->isBlockFlow())
2681 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2683 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2684 pos = Position(editingTextNode, 0);
2690 void InsertTextCommand::input(const DOMString &text, bool selectInsertedText)
2692 Selection selection = endingSelection();
2693 bool adjustDownstream = isFirstVisiblePositionOnLine(VisiblePosition(selection.start().downstream(StayInBlock)));
2695 // Delete the current selection, or collapse whitespace, as needed
2696 if (selection.isRange())
2699 // Delete any insignificant text that could get in the way of whitespace turning
2700 // out correctly after the insertion.
2701 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2703 // Make sure the document is set up to receive text
2704 Position pos = prepareForTextInsertion(adjustDownstream);
2706 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2707 long offset = pos.offset();
2709 // Now that we are about to add content, check to see if a placeholder element
2711 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2713 // These are temporary implementations for inserting adjoining spaces
2714 // into a document. We are working on a CSS-related whitespace solution
2715 // that will replace this some day. We hope.
2717 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2718 // although the number of spaces varies (we choose four spaces).
2719 // Note that there is no attempt to make this work like a real tab stop, it is merely
2720 // a set number of spaces. This also seems to be the HTML editing convention.
2721 for (int i = 0; i < spacesPerTab; i++) {
2722 insertSpace(textNode, offset);
2723 rebalanceWhitespace();
2724 document()->updateLayout();
2726 if (selectInsertedText)
2727 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2729 setEndingSelection(Position(textNode, offset + spacesPerTab));
2730 m_charactersAdded += spacesPerTab;
2732 else if (isWS(text)) {
2733 insertSpace(textNode, offset);
2734 if (selectInsertedText)
2735 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2737 setEndingSelection(Position(textNode, offset + 1));
2738 m_charactersAdded++;
2739 rebalanceWhitespace();
2742 const DOMString &existingText = textNode->data();
2743 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2744 // DOM looks like this:
2745 // character nbsp caret
2746 // As we are about to insert a non-whitespace character at the caret
2747 // convert the nbsp to a regular space.
2748 // EDIT FIXME: This needs to be improved some day to convert back only
2749 // those nbsp's added by the editor to make rendering come out right.
2750 replaceTextInNode(textNode, offset - 1, 1, " ");
2752 insertTextIntoNode(textNode, offset, text);
2753 if (selectInsertedText)
2754 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2756 setEndingSelection(Position(textNode, offset + text.length()));
2757 m_charactersAdded += text.length();
2761 void InsertTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2765 DOMString text(textNode->data());
2767 // count up all spaces and newlines in front of the caret
2768 // delete all collapsed ones
2769 // this will work out OK since the offset we have been passed has been upstream-ized
2771 for (unsigned int i = offset; i < text.length(); i++) {
2778 // By checking the character at the downstream position, we can
2779 // check if there is a rendered WS at the caret
2780 Position pos(textNode, offset);
2781 Position downstream = pos.downstream();
2782 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2783 count--; // leave this WS in
2785 deleteTextFromNode(textNode, offset, count);
2788 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2789 // insert a "regular" space
2790 insertTextIntoNode(textNode, offset, " ");
2794 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2795 // DOM looks like this:
2797 // insert a space between the two nbsps
2798 insertTextIntoNode(textNode, offset - 1, " ");
2803 insertTextIntoNode(textNode, offset, nonBreakingSpaceString());
2806 bool InsertTextCommand::isInsertTextCommand() const
2811 //------------------------------------------------------------------------------------------
2812 // JoinTextNodesCommand
2814 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2815 : EditCommand(document), m_text1(text1), m_text2(text2)
2819 ASSERT(m_text1->nextSibling() == m_text2);
2820 ASSERT(m_text1->length() > 0);
2821 ASSERT(m_text2->length() > 0);
2827 JoinTextNodesCommand::~JoinTextNodesCommand()
2835 void JoinTextNodesCommand::doApply()
2839 ASSERT(m_text1->nextSibling() == m_text2);
2841 int exceptionCode = 0;
2842 m_text2->insertData(0, m_text1->data(), exceptionCode);
2843 ASSERT(exceptionCode == 0);
2845 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2846 ASSERT(exceptionCode == 0);
2848 m_offset = m_text1->length();
2851 void JoinTextNodesCommand::doUnapply()
2854 ASSERT(m_offset > 0);
2856 int exceptionCode = 0;
2858 m_text2->deleteData(0, m_offset, exceptionCode);
2859 ASSERT(exceptionCode == 0);
2861 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2862 ASSERT(exceptionCode == 0);
2864 ASSERT(m_text2->previousSibling()->isTextNode());
2865 ASSERT(m_text2->previousSibling() == m_text1);
2868 //------------------------------------------------------------------------------------------
2869 // MoveSelectionCommand
2871 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2872 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2878 MoveSelectionCommand::~MoveSelectionCommand()
2881 m_fragment->deref();
2884 void MoveSelectionCommand::doApply()
2886 Selection selection = endingSelection();
2887 ASSERT(selection.isRange());
2889 Position pos = m_position;
2891 // Update the position otherwise it may become invalid after the selection is deleted.
2892 NodeImpl *positionNode = m_position.node();
2893 long positionOffset = m_position.offset();
2894 Position selectionEnd = selection.end();
2895 long selectionEndOffset = selectionEnd.offset();
2896 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2897 positionOffset -= selectionEndOffset;
2898 Position selectionStart = selection.start();
2899 if (selectionStart.node() == positionNode) {
2900 positionOffset += selectionStart.offset();
2902 pos = Position(positionNode, positionOffset);
2905 deleteSelection(m_smartMove);
2907 // If the node for the destination has been removed as a result of the deletion,
2908 // set the destination to the ending point after the deletion.
2909 // Fixes: <rdar://problem/3910425> REGRESSION (Mail): Crash in ReplaceSelectionCommand;
2910 // selection is empty, leading to null deref
2911 if (!pos.node()->inDocument())
2912 pos = endingSelection().start();
2914 setEndingSelection(pos);
2915 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2916 applyCommandToComposite(cmd);
2919 EditAction MoveSelectionCommand::editingAction() const
2921 return EditActionDrag;
2924 //------------------------------------------------------------------------------------------
2925 // RebalanceWhitespaceCommand
2927 RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(DocumentImpl *document, const Position &pos)
2928 : EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset), m_downstreamOffset(InvalidOffset)
2932 RebalanceWhitespaceCommand::~RebalanceWhitespaceCommand()
2936 void RebalanceWhitespaceCommand::doApply()
2938 static DOMString space(" ");
2940 if (m_position.isNull() || !m_position.node()->isTextNode())
2943 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
2944 DOMString text = textNode->data();
2945 if (text.length() == 0)
2948 // find upstream offset
2949 long upstream = m_position.offset();
2950 while (upstream > 0 && isWS(text[upstream - 1]) || isNBSP(text[upstream - 1])) {
2952 m_upstreamOffset = upstream;
2955 // find downstream offset
2956 long downstream = m_position.offset();
2957 while ((unsigned)downstream < text.length() && isWS(text[downstream]) || isNBSP(text[downstream])) {
2959 m_downstreamOffset = downstream;
2962 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
2965 m_upstreamOffset = upstream;
2966 m_downstreamOffset = downstream;
2967 long length = m_downstreamOffset - m_upstreamOffset;
2969 m_beforeString = text.substring(m_upstreamOffset, length);
2971 // The following loop figures out a "rebalanced" whitespace string for any length
2972 // string, and takes into account the special cases that need to handled for the
2973 // start and end of strings (i.e. first and last character must be an nbsp.
2974 long i = m_upstreamOffset;
2975 while (i < m_downstreamOffset) {
2976 long add = (m_downstreamOffset - i) % 3;
2979 m_afterString += nonBreakingSpaceString();
2980 m_afterString += space;
2981 m_afterString += nonBreakingSpaceString();
2985 if (i == 0 || (unsigned)i + 1 == text.length()) // at start or end of string
2986 m_afterString += nonBreakingSpaceString();
2988 m_afterString += space;
2991 if ((unsigned)i + 2 == text.length()) {
2993 m_afterString += nonBreakingSpaceString();
2994 m_afterString += nonBreakingSpaceString();
2997 m_afterString += nonBreakingSpaceString();
2998 m_afterString += space;
3005 text.remove(m_upstreamOffset, length);
3006 text.insert(m_afterString, m_upstreamOffset);
3009 void RebalanceWhitespaceCommand::doUnapply()
3011 if (m_upstreamOffset == InvalidOffset && m_downstreamOffset == InvalidOffset)
3014 ASSERT(m_position.node()->isTextNode());
3015 TextImpl *textNode = static_cast<TextImpl *>(m_position.node());
3016 DOMString text = textNode->data();
3017 text.remove(m_upstreamOffset, m_afterString.length());
3018 text.insert(m_beforeString, m_upstreamOffset);
3021 bool RebalanceWhitespaceCommand::preservesTypingStyle() const
3026 //------------------------------------------------------------------------------------------
3027 // RemoveCSSPropertyCommand
3029 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
3030 : EditCommand(document), m_decl(decl->makeMutable()), m_property(property), m_important(false)
3036 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
3042 void RemoveCSSPropertyCommand::doApply()
3046 m_oldValue = m_decl->getPropertyValue(m_property);
3047 ASSERT(!m_oldValue.isNull());
3049 m_important = m_decl->getPropertyPriority(m_property);
3050 m_decl->removeProperty(m_property);
3053 void RemoveCSSPropertyCommand::doUnapply()
3056 ASSERT(!m_oldValue.isNull());
3058 m_decl->setProperty(m_property, m_oldValue, m_important);
3061 //------------------------------------------------------------------------------------------
3062 // RemoveNodeAttributeCommand
3064 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
3065 : EditCommand(document), m_element(element), m_attribute(attribute)
3071 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
3077 void RemoveNodeAttributeCommand::doApply()
3081 m_oldValue = m_element->getAttribute(m_attribute);
3082 ASSERT(!m_oldValue.isNull());
3084 int exceptionCode = 0;
3085 m_element->removeAttribute(m_attribute, exceptionCode);
3086 ASSERT(exceptionCode == 0);
3089 void RemoveNodeAttributeCommand::doUnapply()
3092 ASSERT(!m_oldValue.isNull());
3094 int exceptionCode = 0;
3095 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
3096 ASSERT(exceptionCode == 0);
3099 //------------------------------------------------------------------------------------------
3100 // RemoveNodeCommand
3102 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
3103 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
3105 ASSERT(m_removeChild);
3106 m_removeChild->ref();
3108 m_parent = m_removeChild->parentNode();
3112 m_refChild = m_removeChild->nextSibling();
3117 RemoveNodeCommand::~RemoveNodeCommand()
3122 ASSERT(m_removeChild);
3123 m_removeChild->deref();
3126 m_refChild->deref();
3129 void RemoveNodeCommand::doApply()
3132 ASSERT(m_removeChild);
3134 int exceptionCode = 0;
3135 m_parent->removeChild(m_removeChild, exceptionCode);
3136 ASSERT(exceptionCode == 0);
3139 void RemoveNodeCommand::doUnapply()
3142 ASSERT(m_removeChild);
3144 int exceptionCode = 0;
3145 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
3146 ASSERT(exceptionCode == 0);
3149 //------------------------------------------------------------------------------------------
3150 // RemoveNodePreservingChildrenCommand
3152 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
3153 : CompositeEditCommand(document), m_node(node)
3159 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
3165 void RemoveNodePreservingChildrenCommand::doApply()
3167 while (NodeImpl* curr = node()->firstChild()) {
3169 insertNodeBefore(curr, node());
3174 //------------------------------------------------------------------------------------------
3175 // ReplaceSelectionCommand
3177 ReplacementFragment::ReplacementFragment(DocumentFragmentImpl *fragment)
3178 : m_fragment(fragment), m_hasInterchangeNewline(false), m_hasMoreThanOneBlock(false)
3181 m_type = EmptyFragment;
3187 NodeImpl *firstChild = m_fragment->firstChild();
3188 NodeImpl *lastChild = m_fragment->lastChild();
3191 m_type = EmptyFragment;
3195 if (firstChild == lastChild && firstChild->isTextNode()) {
3196 m_type = SingleTextNodeFragment;
3200 m_type = TreeFragment;
3202 NodeImpl *node = firstChild;
3203 int realBlockCount = 0;
3204 NodeImpl *nodeToDelete = 0;
3206 NodeImpl *next = node->traverseNextNode();
3207 if (isInterchangeNewlineNode(node)) {
3208 m_hasInterchangeNewline = true;
3209 nodeToDelete = node;
3211 else if (isInterchangeConvertedSpaceSpan(node)) {
3213 while ((n = node->firstChild())) {
3216 insertNodeBefore(n, node);
3221 next = n->traverseNextNode();
3223 else if (isProbablyBlock(node))
3229 removeNode(nodeToDelete);
3231 int blockCount = realBlockCount;
3232 firstChild = m_fragment->firstChild();
3233 lastChild = m_fragment->lastChild();
3234 if (!isProbablyBlock(firstChild))
3236 if (!isProbablyBlock(lastChild) && realBlockCount > 0)
3240 m_hasMoreThanOneBlock = true;
3243 ReplacementFragment::~ReplacementFragment()
3246 m_fragment->deref();
3249 NodeImpl *ReplacementFragment::firstChild() const
3251 return m_fragment->firstChild();
3254 NodeImpl *ReplacementFragment::lastChild() const
3256 return m_fragment->lastChild();
3259 NodeImpl *ReplacementFragment::mergeStartNode() const
3261 NodeImpl *node = m_fragment->firstChild();
3264 if (!isProbablyBlock(node))
3266 return node->firstChild();
3269 NodeImpl *ReplacementFragment::mergeEndNode() const
3271 NodeImpl *node = m_fragment->lastChild();
3272 while (node && node->lastChild())
3273 node = node->lastChild();
3275 if (isProbablyBlock(node))
3278 NodeImpl *startingBlock = enclosingBlock(node);
3279 ASSERT(startingBlock != node);
3281 NodeImpl *prev = node->traversePreviousNode();
3282 if (prev == m_fragment || prev == startingBlock || enclosingBlock(prev) != startingBlock)
3290 void ReplacementFragment::pruneEmptyNodes()
3295 NodeImpl *node = m_fragment->firstChild();
3297 if ((node->isTextNode() && static_cast<TextImpl *>(node)->length() == 0) ||
3298 (isProbablyBlock(node) && node->childNodeCount() == 0)) {
3299 NodeImpl *next = node->traverseNextSibling();
3305 node = node->traverseNextNode();
3311 bool ReplacementFragment::isInterchangeNewlineNode(const NodeImpl *node)
3313 static DOMString interchangeNewlineClassString(AppleInterchangeNewline);
3314 return node && node->id() == ID_BR && static_cast<const ElementImpl *>(node)->getAttribute(ATTR_CLASS) == interchangeNewlineClassString;
3317 bool ReplacementFragment::isInterchangeConvertedSpaceSpan(const NodeImpl *node)
3319 static DOMString convertedSpaceSpanClassString(AppleConvertedSpace);
3320 return node->isHTMLElement() && static_cast<const HTMLElementImpl *>(node)->getAttribute(ATTR_CLASS) == convertedSpaceSpanClassString;
3323 NodeImpl *ReplacementFragment::enclosingBlock(NodeImpl *node) const
3325 while (node && !isProbablyBlock(node))
3326 node = node->parentNode();
3327 return node ? node : m_fragment;
3330 void ReplacementFragment::removeNode(NodeImpl *node)
3335 NodeImpl *parent = node->parentNode();
3339 int exceptionCode = 0;
3340 parent->removeChild(node, exceptionCode);
3341 ASSERT(exceptionCode == 0);
3344 void ReplacementFragment::insertNodeBefore(NodeImpl *node, NodeImpl *refNode)
3346 if (!node || !refNode)
3349 NodeImpl *parent = refNode->parentNode();
3353 int exceptionCode = 0;
3354 parent->insertBefore(node, refNode, exceptionCode);
3355 ASSERT(exceptionCode == 0);
3359 bool isProbablyBlock(const NodeImpl *node)
3364 switch (node->id()) {
3390 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
3391 : CompositeEditCommand(document),
3392 m_fragment(fragment),
3393 m_selectReplacement(selectReplacement),
3394 m_smartReplace(smartReplace)
3398 ReplaceSelectionCommand::~ReplaceSelectionCommand()
3402 void ReplaceSelectionCommand::doApply()
3404 Selection selection = endingSelection();
3405 VisiblePosition visibleStart(selection.start());
3406 VisiblePosition visibleEnd(selection.end());
3407 bool startAtStartOfBlock = isFirstVisiblePositionInBlock(visibleStart);
3408 bool startAtEndOfBlock = isLastVisiblePositionInBlock(visibleStart);
3409 bool startAtBlockBoundary = startAtStartOfBlock || startAtEndOfBlock;
3410 NodeImpl *startBlock = selection.start().node()->enclosingBlockFlowElement();
3411 NodeImpl *endBlock = selection.end().node()->enclosingBlockFlowElement();
3412 bool mergeStart = false;
3413 bool mergeEnd = false;
3414 if (startBlock == startBlock->rootEditableElement() && startAtStartOfBlock && startAtEndOfBlock) {
3415 // Empty document. Merge neither start nor end.
3416 mergeStart = mergeEnd = false;
3419 mergeStart = (m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()) && !isStartOfParagraph(visibleStart);
3420 mergeEnd = !m_fragment.hasInterchangeNewline() && m_fragment.hasMoreThanOneBlock() && !isEndOfParagraph(visibleEnd);
3423 Position startPos = Position(selection.start().node()->enclosingBlockFlowElement(), 0);
3425 EStayInBlock upstreamStayInBlock = StayInBlock;
3427 // Delete the current selection, or collapse whitespace, as needed
3428 if (selection.isRange()) {
3429 deleteSelection(false, !(m_fragment.hasInterchangeNewline() || m_fragment.hasMoreThanOneBlock()));
3431 else if (selection.isCaret() && mergeEnd && !startAtBlockBoundary) {
3432 // The start and the end need to wind up in separate blocks.
3433 // Insert a paragraph separator to make that happen.
3434 insertParagraphSeparator();
3435 upstreamStayInBlock = DoNotStayInBlock;
3438 selection = endingSelection();
3439 if (startAtStartOfBlock && startBlock->inDocument())
3440 startPos = Position(startBlock, 0);
3441 else if (startAtEndOfBlock)
3442 startPos = selection.start().downstream(StayInBlock);
3444 startPos = selection.start().upstream(upstreamStayInBlock);
3445 endPos = selection.end().downstream();
3447 // This command does not use any typing style that is set as a residual effect of
3449 // FIXME: Improve typing style.
3450 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3451 KHTMLPart *part = document()->part();
3452 part->clearTypingStyle();
3455 if (!m_fragment.firstChild())
3458 // Now that we are about to add content, check to see if a placeholder element
3460 NodeImpl *block = startPos.node()->enclosingBlockFlowElement();
3461 NodeImpl *placeholderBlock = 0;
3462 if (removeBlockPlaceholderIfNeeded(block)) {
3463 placeholderBlock = block;
3464 Position pos = Position(block, 0);
3465 if (!endPos.node()->inDocument()) // endPos might have been in the placeholder just removed.
3470 bool addLeadingSpace = false;
3471 bool addTrailingSpace = false;
3472 if (m_smartReplace) {
3473 addLeadingSpace = startPos.leadingWhitespacePosition().isNotNull();
3474 if (addLeadingSpace) {
3475 QChar previousChar = VisiblePosition(startPos).previous().character();
3476 if (!previousChar.isNull()) {
3477 addLeadingSpace = !part->isCharacterSmartReplaceExempt(previousChar, true);
3480 addTrailingSpace = endPos.trailingWhitespacePosition().isNotNull();
3481 if (addTrailingSpace) {
3482 QChar thisChar = VisiblePosition(endPos).character();
3483 if (!thisChar.isNull()) {
3484 addTrailingSpace = !part->isCharacterSmartReplaceExempt(thisChar, false);
3489 document()->updateLayout();
3491 Position insertionPos = startPos;
3492 NodeImpl *firstNodeInserted = 0;
3493 NodeImpl *lastNodeInserted = 0;
3494 bool lastNodeInsertedInMergeEnd = false;
3496 // prune empty nodes from fragment
3497 m_fragment.pruneEmptyNodes();
3499 // Merge content into the end block, if necessary.
3501 NodeImpl *node = m_fragment.mergeEndNode();
3503 NodeImpl *refNode = node;
3504 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3505 insertNodeAt(refNode, endPos.node(), endPos.offset());
3506 firstNodeInserted = refNode;
3507 lastNodeInserted = refNode;
3508 while (node && !isProbablyBlock(node)) {
3509 NodeImpl *next = node->nextSibling();
3510 insertNodeAfter(node, refNode);
3511 lastNodeInserted = node;
3515 lastNodeInsertedInMergeEnd = true;
3519 // prune empty nodes from fragment
3520 m_fragment.pruneEmptyNodes();
3522 // Merge content into the start block, if necessary.
3524 NodeImpl *node = m_fragment.mergeStartNode();
3525 NodeImpl *insertionNode = 0;
3527 NodeImpl *refNode = node;
3528 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3529 insertNodeAt(refNode, startPos.node(), startPos.offset());
3530 firstNodeInserted = refNode;
3531 if (!lastNodeInsertedInMergeEnd)
3532 lastNodeInserted = refNode;
3533 insertionNode = refNode;
3534 while (node && !isProbablyBlock(node)) {
3535 NodeImpl *next = node->nextSibling();
3536 insertNodeAfter(node, refNode);
3537 if (!lastNodeInsertedInMergeEnd)
3538 lastNodeInserted = node;
3539 insertionNode = node;
3544 if (insertionNode) {
3545 if (insertionNode->isTextNode())
3546 insertionPos = Position(insertionNode, insertionNode->caretMaxOffset());
3547 else if (insertionNode->childNodeCount() > 0)
3548 insertionPos = Position(insertionNode, insertionNode->childNodeCount());
3550 insertionPos = Position(insertionNode->parentNode(), insertionNode->nodeIndex() + 1);
3554 // prune empty nodes from fragment
3555 m_fragment.pruneEmptyNodes();
3557 // Merge everything remaining.
3558 NodeImpl *node = m_fragment.firstChild();
3560 NodeImpl *refNode = node;
3561 NodeImpl *node = refNode ? refNode->nextSibling() : 0;
3562 VisiblePosition visiblePos(insertionPos);
3563 bool insertionNodeIsBody = insertionPos.node()->id() == ID_BODY;
3564 if (!mergeStart && !insertionNodeIsBody && isProbablyBlock(refNode) && isStartOfParagraph(visiblePos)) {
3565 Position pos = insertionPos;
3566 if (!insertionPos.node()->isTextNode() && !insertionPos.node()->isBlockFlow() && insertionPos.offset() > 0)
3567 pos = insertionPos.downstream(StayInBlock);
3568 insertNodeBefore(refNode, pos.node());
3570 else if (!mergeEnd && !insertionNodeIsBody && isProbablyBlock(refNode) && isEndOfParagraph(visiblePos))
3571 insertNodeAfter(refNode, insertionPos.node());
3573 insertNodeAt(refNode, insertionPos.node(), insertionPos.offset());
3574 if (!firstNodeInserted)
3575 firstNodeInserted = refNode;
3576 if (!lastNodeInsertedInMergeEnd)
3577 lastNodeInserted = refNode;
3579 NodeImpl *next = node->nextSibling();
3580 insertNodeAfter(node, refNode);
3581 if (!lastNodeInsertedInMergeEnd)
3582 lastNodeInserted = node;
3586 document()->updateLayout();
3587 insertionPos = Position(lastNodeInserted, lastNodeInserted->caretMaxOffset());
3590 // Handle "smart replace" whitespace
3591 if (addTrailingSpace && lastNodeInserted) {
3592 if (lastNodeInserted->isTextNode()) {
3593 TextImpl *text = static_cast<TextImpl *>(lastNodeInserted);
3594 insertTextIntoNode(text, text->length(), nonBreakingSpaceString());
3595 insertionPos = Position(text, text->length());
3598 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3599 insertNodeAfter(node, lastNodeInserted);
3600 if (!firstNodeInserted)
3601 firstNodeInserted = node;
3602 lastNodeInserted = node;
3603 insertionPos = Position(node, 1);
3607 if (addLeadingSpace && firstNodeInserted) {
3608 if (firstNodeInserted->isTextNode()) {
3609 TextImpl *text = static_cast<TextImpl *>(firstNodeInserted);
3610 insertTextIntoNode(text, 0, nonBreakingSpaceString());
3613 NodeImpl *node = document()->createEditingTextNode(nonBreakingSpaceString());
3614 insertNodeBefore(node, firstNodeInserted);
3615 firstNodeInserted = node;
3616 if (!lastNodeInsertedInMergeEnd)
3617 lastNodeInserted = node;
3621 // Handle trailing newline
3622 if (m_fragment.hasInterchangeNewline()) {
3623 if (startBlock == endBlock && !isProbablyBlock(lastNodeInserted)) {
3624 setEndingSelection(insertionPos);
3625 insertParagraphSeparator();
3626 endPos = endingSelection().end().downstream();
3628 completeHTMLReplacement(startPos, endPos);
3631 if (lastNodeInserted->id() == ID_BR && !document()->inStrictMode()) {
3632 document()->updateLayout();
3633 VisiblePosition pos(Position(lastNodeInserted, 0));
3634 if (isLastVisiblePositionInBlock(pos)) {
3635 NodeImpl *next = lastNodeInserted->traverseNextNode();
3636 bool hasTrailingBR = next && next->id() == ID_BR && lastNodeInserted->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
3637 if (!hasTrailingBR) {
3638 // Insert an "extra" BR at the end of the block.
3639 insertNodeBefore(createBreakElement(document()), lastNodeInserted);
3643 completeHTMLReplacement(firstNodeInserted, lastNodeInserted);
3646 if (placeholderBlock && placeholderBlock->childNodeCount() == 0) {
3647 removeNode(placeholderBlock);
3651 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &start, const Position &end)
3653 if (start.isNull() || !start.node()->inDocument() || end.isNull() || !end.node()->inDocument())
3655 m_selectReplacement ? setEndingSelection(Selection(start, end)) : setEndingSelection(end);
3656 rebalanceWhitespace();
3659 void ReplaceSelectionCommand::completeHTMLReplacement(NodeImpl *firstNodeInserted, NodeImpl *lastNodeInserted)
3661 if (!firstNodeInserted || !firstNodeInserted->inDocument() ||
3662 !lastNodeInserted || !lastNodeInserted->inDocument())
3665 // Find the last leaf.
3666 NodeImpl *lastLeaf = lastNodeInserted;
3668 NodeImpl *nextChild = lastLeaf->lastChild();
3671 lastLeaf = nextChild;
3674 // Find the first leaf.
3675 NodeImpl *firstLeaf = firstNodeInserted;
3677 NodeImpl *nextChild = firstLeaf->firstChild();
3680 firstLeaf = nextChild;
3683 Position start(firstLeaf, firstLeaf->caretMinOffset());
3684 Position end(lastLeaf, lastLeaf->caretMaxOffset());
3685 Selection replacementSelection(start, end);
3686 if (m_selectReplacement) {
3687 // Select what was inserted.
3688 setEndingSelection(replacementSelection);
3691 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
3692 setEndingSelection(end);
3694 rebalanceWhitespace();
3697 //------------------------------------------------------------------------------------------
3698 // SetNodeAttributeCommand
3700 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
3701 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
3705 ASSERT(!m_value.isNull());
3708 SetNodeAttributeCommand::~SetNodeAttributeCommand()
3714 void SetNodeAttributeCommand::doApply()
3717 ASSERT(!m_value.isNull());
3719 int exceptionCode = 0;
3720 m_oldValue = m_element->getAttribute(m_attribute);
3721 m_element->setAttribute(m_attribute, m_value.implementation(), exceptionCode);
3722 ASSERT(exceptionCode == 0);
3725 void SetNodeAttributeCommand::doUnapply()
3728 ASSERT(!m_oldValue.isNull());
3730 int exceptionCode = 0;
3731 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
3732 ASSERT(exceptionCode == 0);
3735 //------------------------------------------------------------------------------------------
3736 // SplitTextNodeCommand
3738 SplitTextNodeCommand::SplitTextNodeCommand(DocumentImpl *document, TextImpl *text, long offset)
3739 : EditCommand(document), m_text1(0), m_text2(text), m_offset(offset)
3742 ASSERT(m_text2->length() > 0);
3747 SplitTextNodeCommand::~SplitTextNodeCommand()
3756 void SplitTextNodeCommand::doApply()
3759 ASSERT(m_offset > 0);
3761 int exceptionCode = 0;
3763 // EDIT FIXME: This should use better smarts for figuring out which portion
3764 // of the split to copy (based on their comparitive sizes). We should also
3765 // just use the DOM's splitText function.
3768 // create only if needed.
3769 // if reapplying, this object will already exist.
3770 m_text1 = document()->createTextNode(m_text2->substringData(0, m_offset, exceptionCode));
3771 ASSERT(exceptionCode == 0);
3776 m_text2->deleteData(0, m_offset, exceptionCode);
3777 ASSERT(exceptionCode == 0);
3779 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
3780 ASSERT(exceptionCode == 0);
3782 ASSERT(m_text2->previousSibling()->isTextNode());
3783 ASSERT(m_text2->previousSibling() == m_text1);
3786 void SplitTextNodeCommand::doUnapply()
3791 ASSERT(m_text1->nextSibling() == m_text2);
3793 int exceptionCode = 0;
3794 m_text2->insertData(0, m_text1->data(), exceptionCode);
3795 ASSERT(exceptionCode == 0);
3797 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
3798 ASSERT(exceptionCode == 0);
3800 m_offset = m_text1->length();
3803 //------------------------------------------------------------------------------------------
3806 TypingCommand::TypingCommand(DocumentImpl *document, ETypingCommand commandType, const DOMString &textToInsert, bool selectInsertedText)
3807 : CompositeEditCommand(document), m_commandType(commandType), m_textToInsert(textToInsert), m_openForMoreTyping(true), m_applyEditing(false), m_selectInsertedText(selectInsertedText)
3811 void TypingCommand::deleteKeyPressed(DocumentImpl *document)
3815 KHTMLPart *part = document->part();
3818 EditCommandPtr lastEditCommand = part->lastEditCommand();
3819 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3820 static_cast<TypingCommand *>(lastEditCommand.get())->deleteKeyPressed();
3823 EditCommandPtr cmd(new TypingCommand(document, DeleteKey));
3828 void TypingCommand::insertText(DocumentImpl *document, const DOMString &text, bool selectInsertedText)
3832 KHTMLPart *part = document->part();
3835 EditCommandPtr lastEditCommand = part->lastEditCommand();
3836 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3837 static_cast<TypingCommand *>(lastEditCommand.get())->insertText(text, selectInsertedText);
3840 EditCommandPtr cmd(new TypingCommand(document, InsertText, text, selectInsertedText));
3845 void TypingCommand::insertLineBreak(DocumentImpl *document)
3849 KHTMLPart *part = document->part();
3852 EditCommandPtr lastEditCommand = part->lastEditCommand();
3853 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3854 static_cast<TypingCommand *>(lastEditCommand.get())->insertLineBreak();
3857 EditCommandPtr cmd(new TypingCommand(document, InsertLineBreak));
3862 void TypingCommand::insertParagraphSeparatorInQuotedContent(DocumentImpl *document)
3866 KHTMLPart *part = document->part();
3869 EditCommandPtr lastEditCommand = part->lastEditCommand();
3870 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3871 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparatorInQuotedContent();
3874 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparatorInQuotedContent));
3879 void TypingCommand::insertParagraphSeparator(DocumentImpl *document)
3883 KHTMLPart *part = document->part();
3886 EditCommandPtr lastEditCommand = part->lastEditCommand();
3887 if (isOpenForMoreTypingCommand(lastEditCommand)) {
3888 static_cast<TypingCommand *>(lastEditCommand.get())->insertParagraphSeparator();
3891 EditCommandPtr cmd(new TypingCommand(document, InsertParagraphSeparator));
3896 bool TypingCommand::isOpenForMoreTypingCommand(const EditCommandPtr &cmd)
3898 return cmd.isTypingCommand() &&
3899 static_cast<const TypingCommand *>(cmd.get())->openForMoreTyping();
3902 void TypingCommand::closeTyping(const EditCommandPtr &cmd)
3904 if (isOpenForMoreTypingCommand(cmd))
3905 static_cast<TypingCommand *>(cmd.get())->closeTyping();
3908 void TypingCommand::doApply()
3910 if (endingSelection().isNone())
3913 switch (m_commandType) {
3917 case InsertLineBreak:
3920 case InsertParagraphSeparator:
3921 insertParagraphSeparator();
3923 case InsertParagraphSeparatorInQuotedContent:
3924 insertParagraphSeparatorInQuotedContent();
3927 insertText(m_textToInsert, m_selectInsertedText);
3931 ASSERT_NOT_REACHED();
3934 EditAction TypingCommand::editingAction() const
3936 return EditActionTyping;
3939 void TypingCommand::markMisspellingsAfterTyping()
3941 // Take a look at the selection that results after typing and determine whether we need to spellcheck.
3942 // Since the word containing the current selection is never marked, this does a check to
3943 // see if typing made a new word that is not in the current selection. Basically, you
3944 // get this by being at the end of a word and typing a space.
3945 VisiblePosition start(endingSelection().start());
3946 VisiblePosition previous = start.previous();
3947 if (previous.isNotNull()) {
3948 VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
3949 VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
3951 KWQ(document()->part())->markMisspellingsInAdjacentWords(p1);
3955 void TypingCommand::typingAddedToOpenCommand()
3957 markMisspellingsAfterTyping();
3958 // Do not apply editing to the part on the first time through.
3959 // The part will get told in the same way as all other commands.
3960 // But since this command stays open and is used for additional typing,
3961 // we need to tell the part here as other commands are added.
3962 if (m_applyEditing) {
3963 EditCommandPtr cmd(this);
3964 document()->part()->appliedEditing(cmd);
3966 m_applyEditing = true;
3969 void TypingCommand::insertText(const DOMString &text, bool selectInsertedText)
3971 // FIXME: Improve typing style.
3972 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
3973 if (document()->part()->typingStyle() || m_cmds.count() == 0) {
3974 InsertTextCommand *impl = new InsertTextCommand(document());
3975 EditCommandPtr cmd(impl);
3976 applyCommandToComposite(cmd);
3977 impl->input(text, selectInsertedText);
3980 EditCommandPtr lastCommand = m_cmds.last();
3981 if (lastCommand.isInsertTextCommand()) {
3982 InsertTextCommand *impl = static_cast<InsertTextCommand *>(lastCommand.get());
3983 impl->input(text, selectInsertedText);
3986 InsertTextCommand *impl = new InsertTextCommand(document());
3987 EditCommandPtr cmd(impl);
3988 applyCommandToComposite(cmd);
3989 impl->input(text, selectInsertedText);
3992 typingAddedToOpenCommand();
3995 void TypingCommand::insertLineBreak()
3997 EditCommandPtr cmd(new InsertLineBreakCommand(document()));
3998 applyCommandToComposite(cmd);
3999 typingAddedToOpenCommand();
4002 void TypingCommand::insertParagraphSeparator()
4004 EditCommandPtr cmd(new InsertParagraphSeparatorCommand(document()));
4005 applyCommandToComposite(cmd);
4006 typingAddedToOpenCommand();
4009 void TypingCommand::insertParagraphSeparatorInQuotedContent()
4011 EditCommandPtr cmd(new InsertParagraphSeparatorInQuotedContentCommand(document()));
4012 applyCommandToComposite(cmd);
4013 typingAddedToOpenCommand();
4016 void TypingCommand::issueCommandForDeleteKey()
4018 Selection selectionToDelete;
4020 switch (endingSelection().state()) {
4021 case Selection::RANGE:
4022 selectionToDelete = endingSelection();
4024 case Selection::CARET: {
4025 // Handle delete at beginning-of-block case.
4026 // Do nothing in the case that the caret is at the start of a
4027 // root editable element or at the start of a document.
4028 Position pos(endingSelection().start());
4029 Position start = VisiblePosition(pos).previous().deepEquivalent();
4030 Position end = VisiblePosition(pos).deepEquivalent();
4031 if (start.isNotNull() && end.isNotNull() && start.node()->rootEditableElement() == end.node()->rootEditableElement())
4032 selectionToDelete = Selection(start, end);
4035 case Selection::NONE:
4036 ASSERT_NOT_REACHED();
4040 if (selectionToDelete.isCaretOrRange()) {
4041 deleteSelection(selectionToDelete);
4042 typingAddedToOpenCommand();
4046 void TypingCommand::deleteKeyPressed()
4048 // EDIT FIXME: The ifdef'ed out code below should be re-enabled.
4049 // In order for this to happen, the deleteCharacter case
4050 // needs work. Specifically, the caret-positioning code
4051 // and whitespace-handling code in DeleteSelectionCommand::doApply()
4052 // needs to be factored out so it can be used again here.
4053 // Until that work is done, issueCommandForDeleteKey() does the
4054 // right thing, but less efficiently and with the cost of more
4056 issueCommandForDeleteKey();
4058 if (m_cmds.count() == 0) {
4059 issueCommandForDeleteKey();
4062 EditCommandPtr lastCommand = m_cmds.last();
4063 if (lastCommand.isInsertTextCommand()) {
4064 InsertTextCommand &cmd = static_cast<InsertTextCommand &>(lastCommand);
4065 cmd.deleteCharacter();
4066 if (cmd.charactersAdded() == 0) {
4067 removeCommand(lastCommand);
4070 else if (lastCommand.isInsertLineBreakCommand()) {
4071 lastCommand.unapply();
4072 removeCommand(lastCommand);
4075 issueCommandForDeleteKey();
4081 void TypingCommand::removeCommand(const EditCommandPtr &cmd)
4083 // NOTE: If the passed-in command is the last command in the
4084 // composite, we could remove all traces of this typing command
4085 // from the system, including the undo chain. Other editors do
4086 // not do this, but we could.
4089 if (m_cmds.count() == 0)
4090 setEndingSelection(startingSelection());
4092 setEndingSelection(m_cmds.last().endingSelection());
4095 EditAction ReplaceSelectionCommand::editingAction() const
4097 return EditActionPaste;
4100 bool TypingCommand::preservesTypingStyle() const
4102 switch (m_commandType) {
4104 case InsertParagraphSeparator:
4105 case InsertLineBreak:
4107 case InsertParagraphSeparatorInQuotedContent:
4111 ASSERT_NOT_REACHED();
4115 bool TypingCommand::isTypingCommand() const
4120 ElementImpl *createDefaultParagraphElement(DocumentImpl *document)
4122 static const DOMString defaultParagraphStyle("margin-top: 0; margin-bottom: 0");
4123 int exceptionCode = 0;
4124 ElementImpl *element = document->createHTMLElement("p", exceptionCode);
4125 ASSERT(exceptionCode == 0);
4126 element->setAttribute(ATTR_STYLE, defaultParagraphStyle);
4130 ElementImpl *createBlockPlaceholderElement(DocumentImpl *document)
4132 int exceptionCode = 0;
4133 ElementImpl *breakNode = document->createHTMLElement("br", exceptionCode);
4134 ASSERT(exceptionCode == 0);
4135 breakNode->setAttribute(ATTR_CLA