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 "htmlattrs.h"
46 #include "khtml_part.h"
47 #include "khtml_part.h"
48 #include "khtmlview.h"
50 #include "render_object.h"
51 #include "render_style.h"
52 #include "render_text.h"
53 #include "visible_position.h"
54 #include "visible_units.h"
57 using DOM::CSSComputedStyleDeclarationImpl;
58 using DOM::CSSPrimitiveValue;
59 using DOM::CSSPrimitiveValueImpl;
60 using DOM::CSSProperty;
61 using DOM::CSSStyleDeclarationImpl;
62 using DOM::CSSValueImpl;
63 using DOM::DocumentFragmentImpl;
64 using DOM::DocumentImpl;
66 using DOM::DOMStringImpl;
67 using DOM::DoNotUpdateLayout;
68 using DOM::EditingTextImpl;
69 using DOM::ElementImpl;
70 using DOM::HTMLElementImpl;
71 using DOM::HTMLImageElementImpl;
72 using DOM::NamedAttrMapImpl;
75 using DOM::NodeListImpl;
77 using DOM::PositionIterator;
80 using DOM::StayInBlock;
82 using DOM::TreeWalkerImpl;
85 #include "KWQAssertions.h"
86 #include "KWQLogging.h"
87 #include "KWQKHTMLPart.h"
91 #define ASSERT(assertion) ((void)0)
92 #define ASSERT_WITH_MESSAGE(assertion, formatAndArgs...) ((void)0)
93 #define ASSERT_NOT_REACHED() ((void)0)
94 #define LOG(channel, formatAndArgs...) ((void)0)
95 #define ERROR(formatAndArgs...) ((void)0)
96 #define ASSERT(assertion) assert(assertion)
98 #define debugPosition(a,b) ((void)0)
102 #define IF_IMPL_NULL_RETURN_ARG(arg) do { \
103 if (isNull()) { return arg; } \
106 #define IF_IMPL_NULL_RETURN do { \
107 if (isNull()) { return; } \
112 static inline bool isNBSP(const QChar &c)
114 return c == QChar(0xa0);
117 static inline bool isWS(const QChar &c)
119 return c.isSpace() && c != QChar(0xa0);
122 static inline bool isWS(const DOMString &text)
124 if (text.length() != 1)
127 return isWS(text[0]);
130 static inline bool isWS(const Position &pos)
135 if (!pos.node()->isTextNode())
138 const DOMString &string = static_cast<TextImpl *>(pos.node())->data();
139 return isWS(string[pos.offset()]);
142 static const int spacesPerTab = 4;
144 static inline bool isTab(const DOMString &text)
146 static QChar tabCharacter = QChar(0x9);
147 if (text.length() != 1)
150 return text[0] == tabCharacter;
153 static inline bool isTableStructureNode(const NodeImpl *node)
155 RenderObject *r = node->renderer();
156 return (r && (r->isTableCell() || r->isTableRow() || r->isTableSection() || r->isTableCol()));
159 static DOMString &nonBreakingSpaceString()
161 static DOMString nonBreakingSpaceString = QString(QChar(0xa0));
162 return nonBreakingSpaceString;
165 static DOMString &styleSpanClassString()
167 static DOMString styleSpanClassString = "khtml-style-span";
168 return styleSpanClassString;
171 static DOMString &blockPlaceholderClassString()
173 static DOMString blockPlaceholderClassString = "khtml-block-placeholder";
174 return blockPlaceholderClassString;
177 static void debugPosition(const char *prefix, const Position &pos)
182 LOG(Editing, "%s <null>", prefix);
184 LOG(Editing, "%s%s %p : %d", prefix, getTagName(pos.node()->id()).string().latin1(), pos.node(), pos.offset());
187 //------------------------------------------------------------------------------------------
190 EditCommandPtr::EditCommandPtr()
194 EditCommandPtr::EditCommandPtr(EditCommand *impl) : SharedPtr<EditCommand>(impl)
198 EditCommandPtr::EditCommandPtr(const EditCommandPtr &o) : SharedPtr<EditCommand>(o)
202 EditCommandPtr::~EditCommandPtr()
206 EditCommandPtr &EditCommandPtr::operator=(const EditCommandPtr &c)
208 static_cast<SharedPtr<EditCommand> &>(*this) = c;
212 bool EditCommandPtr::isCompositeStep() const
214 IF_IMPL_NULL_RETURN_ARG(false);
215 return get()->isCompositeStep();
218 bool EditCommandPtr::isInputTextCommand() const
220 IF_IMPL_NULL_RETURN_ARG(false);
221 return get()->isInputTextCommand();
224 bool EditCommandPtr::isTypingCommand() const
226 IF_IMPL_NULL_RETURN_ARG(false);
227 return get()->isTypingCommand();
230 void EditCommandPtr::apply() const
236 void EditCommandPtr::unapply() const
242 void EditCommandPtr::reapply() const
248 DocumentImpl * const EditCommandPtr::document() const
250 IF_IMPL_NULL_RETURN_ARG(0);
251 return get()->document();
254 Selection EditCommandPtr::startingSelection() const
256 IF_IMPL_NULL_RETURN_ARG(Selection());
257 return get()->startingSelection();
260 Selection EditCommandPtr::endingSelection() const
262 IF_IMPL_NULL_RETURN_ARG(Selection());
263 return get()->endingSelection();
266 void EditCommandPtr::setStartingSelection(const Selection &s) const
269 get()->setStartingSelection(s);
272 void EditCommandPtr::setEndingSelection(const Selection &s) const
275 get()->setEndingSelection(s);
278 CSSStyleDeclarationImpl *EditCommandPtr::typingStyle() const
280 IF_IMPL_NULL_RETURN_ARG(0);
281 return get()->typingStyle();
284 void EditCommandPtr::setTypingStyle(CSSStyleDeclarationImpl *style) const
287 get()->setTypingStyle(style);
290 EditCommandPtr EditCommandPtr::parent() const
292 IF_IMPL_NULL_RETURN_ARG(0);
293 return get()->parent();
296 void EditCommandPtr::setParent(const EditCommandPtr &cmd) const
299 get()->setParent(cmd.get());
302 EditCommandPtr &EditCommandPtr::emptyCommand()
304 static EditCommandPtr m_emptyCommand;
305 return m_emptyCommand;
308 //------------------------------------------------------------------------------------------
311 StyleChange::StyleChange(CSSStyleDeclarationImpl *style)
313 init(style, Position());
316 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position)
318 init(style, position);
321 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
324 m_applyItalic = false;
328 for (QPtrListIterator<CSSProperty> it(*(style->values())); it.current(); ++it) {
329 CSSProperty *property = it.current();
331 // If position is empty or the position passed in already has the
332 // style, just move on.
333 if (position.isNotNull() && currentlyHasStyle(position, property))
336 // Figure out the manner of change that is needed.
337 DOMString valueText(property->value()->cssText());
338 switch (property->id()) {
339 case CSS_PROP_FONT_WEIGHT:
340 if (strcasecmp(valueText, "bold") == 0) {
345 case CSS_PROP_FONT_STYLE:
346 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
347 m_applyItalic = true;
353 styleText += property->cssText().string();
356 m_cssStyle = styleText.stripWhiteSpace();
359 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
361 ASSERT(pos.isNotNull());
362 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
365 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
367 return value && strcasecmp(value->cssText(), property->value()->cssText()) == 0;
370 //------------------------------------------------------------------------------------------
373 EditCommand::EditCommand(DocumentImpl *document)
374 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
377 ASSERT(m_document->part());
379 m_startingSelection = m_document->part()->selection();
380 m_endingSelection = m_startingSelection;
382 m_document->part()->setSelection(Selection(), false, true);
385 EditCommand::~EditCommand()
390 m_typingStyle->deref();
393 void EditCommand::apply()
396 ASSERT(m_document->part());
397 ASSERT(state() == NotApplied);
399 KHTMLPart *part = m_document->part();
401 ASSERT(part->selection().isNone());
407 // FIXME: Improve typing style.
408 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
409 if (!preservesTypingStyle())
412 if (!isCompositeStep()) {
413 document()->updateLayout();
414 EditCommandPtr cmd(this);
415 part->appliedEditing(cmd);
419 void EditCommand::unapply()
422 ASSERT(m_document->part());
423 ASSERT(state() == Applied);
425 bool topLevel = !isCompositeStep();
427 KHTMLPart *part = m_document->part();
430 part->setSelection(Selection(), false, true);
432 ASSERT(part->selection().isNone());
436 m_state = NotApplied;
439 document()->updateLayout();
440 EditCommandPtr cmd(this);
441 part->unappliedEditing(cmd);
445 void EditCommand::reapply()
448 ASSERT(m_document->part());
449 ASSERT(state() == NotApplied);
451 bool topLevel = !isCompositeStep();
453 KHTMLPart *part = m_document->part();
456 part->setSelection(Selection(), false, true);
458 ASSERT(part->selection().isNone());
465 document()->updateLayout();
466 EditCommandPtr cmd(this);
467 part->reappliedEditing(cmd);
471 void EditCommand::doReapply()
476 void EditCommand::setStartingSelection(const Selection &s)
478 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
479 cmd->m_startingSelection = s;
482 void EditCommand::setEndingSelection(const Selection &s)
484 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
485 cmd->m_endingSelection = s;
488 void EditCommand::assignTypingStyle(CSSStyleDeclarationImpl *style)
490 CSSStyleDeclarationImpl *old = m_typingStyle;
491 m_typingStyle = style;
493 m_typingStyle->ref();
498 void EditCommand::setTypingStyle(CSSStyleDeclarationImpl *style)
500 // FIXME: Improve typing style.
501 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
502 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
503 cmd->assignTypingStyle(style);
506 bool EditCommand::preservesTypingStyle() const
511 bool EditCommand::isInputTextCommand() const
516 bool EditCommand::isTypingCommand() const
521 //------------------------------------------------------------------------------------------
522 // CompositeEditCommand
524 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
525 : EditCommand(document)
529 void CompositeEditCommand::doUnapply()
531 if (m_cmds.count() == 0) {
535 for (int i = m_cmds.count() - 1; i >= 0; --i)
536 m_cmds[i]->unapply();
538 setState(NotApplied);
541 void CompositeEditCommand::doReapply()
543 if (m_cmds.count() == 0) {
547 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
554 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
556 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
558 cmd.setStartingSelection(endingSelection());
559 cmd.setEndingSelection(endingSelection());
565 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
567 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
568 applyCommandToComposite(cmd);
571 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
573 if (refChild->parentNode()->lastChild() == refChild) {
574 appendNode(insertChild, refChild->parentNode());
577 ASSERT(refChild->nextSibling());
578 insertNodeBefore(insertChild, refChild->nextSibling());
582 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
584 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
585 NodeImpl *child = refChild->firstChild();
586 for (long i = 0; child && i < offset; i++)
587 child = child->nextSibling();
589 insertNodeBefore(insertChild, child);
591 appendNode(insertChild, refChild);
593 else if (refChild->caretMinOffset() >= offset) {
594 insertNodeBefore(insertChild, refChild);
596 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
597 splitTextNode(static_cast<TextImpl *>(refChild), offset);
598 insertNodeBefore(insertChild, refChild);
601 insertNodeAfter(insertChild, refChild);
605 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
607 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
608 applyCommandToComposite(cmd);
611 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
613 if (isTableStructureNode(node)) {
614 // Do not remove an element of table structure; remove its contents.
615 NodeImpl *child = node->firstChild();
617 NodeImpl *remove = child;
618 child = child->nextSibling();
619 removeFullySelectedNode(remove);
623 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
624 applyCommandToComposite(cmd);
628 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
630 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
631 applyCommandToComposite(cmd);
634 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
636 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
637 applyCommandToComposite(cmd);
640 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
642 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
643 applyCommandToComposite(cmd);
646 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
648 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
649 applyCommandToComposite(cmd);
652 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
654 InputTextCommand *impl = new InputTextCommand(document());
655 EditCommandPtr cmd(impl);
656 applyCommandToComposite(cmd);
657 impl->input(text, selectInsertedText);
660 void CompositeEditCommand::insertText(TextImpl *node, long offset, const DOMString &text)
662 EditCommandPtr cmd(new InsertTextCommand(document(), node, offset, text));
663 applyCommandToComposite(cmd);
666 void CompositeEditCommand::deleteText(TextImpl *node, long offset, long count)
668 EditCommandPtr cmd(new DeleteTextCommand(document(), node, offset, count));
669 applyCommandToComposite(cmd);
672 void CompositeEditCommand::replaceText(TextImpl *node, long offset, long count, const DOMString &replacementText)
674 EditCommandPtr deleteCommand(new DeleteTextCommand(document(), node, offset, count));
675 applyCommandToComposite(deleteCommand);
676 EditCommandPtr insertCommand(new InsertTextCommand(document(), node, offset, replacementText));
677 applyCommandToComposite(insertCommand);
680 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
682 if (endingSelection().isRange()) {
683 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
684 applyCommandToComposite(cmd);
688 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
690 if (selection.isRange()) {
691 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
692 applyCommandToComposite(cmd);
696 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
698 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
699 applyCommandToComposite(cmd);
702 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
704 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
705 applyCommandToComposite(cmd);
708 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
710 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
711 applyCommandToComposite(cmd);
714 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
716 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
717 // and ApplyStyleCommand::computeStyleChange.
718 // Both function do similar work, and the common parts could be factored out.
720 // FIXME: Improve typing style.
721 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
723 // update document layout once before running the rest of the function
724 // so that we avoid the expense of updating before each and every call
725 // to check a computed style
726 document()->updateLayout();
728 StyleChange styleChange(document()->part()->typingStyle());
730 NodeImpl *childToAppend = child;
731 int exceptionCode = 0;
733 if (styleChange.applyItalic()) {
734 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
735 ASSERT(exceptionCode == 0);
736 italicElement->appendChild(childToAppend, exceptionCode);
737 ASSERT(exceptionCode == 0);
738 childToAppend = italicElement;
741 if (styleChange.applyBold()) {
742 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
743 ASSERT(exceptionCode == 0);
744 boldElement->appendChild(childToAppend, exceptionCode);
745 ASSERT(exceptionCode == 0);
746 childToAppend = boldElement;
749 if (styleChange.cssStyle().length() > 0) {
750 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
751 ASSERT(exceptionCode == 0);
752 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
753 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
754 styleElement->appendChild(childToAppend, exceptionCode);
755 ASSERT(exceptionCode == 0);
756 childToAppend = styleElement;
759 return childToAppend;
762 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
764 if (!textNode || !textNode->renderer() || start >= end)
767 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
768 InlineTextBox *box = textRenderer->firstTextBox();
770 // whole text node is empty
771 removeNode(textNode);
775 long length = textNode->length();
776 if (start >= length || end > length)
780 InlineTextBox *prevBox = 0;
781 DOMStringImpl *str = 0;
783 // This loop structure works to process all gaps preceding a box,
784 // and also will look at the gap after the last box.
785 while (prevBox || box) {
786 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
788 // No more chance for any intersections
791 int gapEnd = box ? box->m_start : length;
792 bool indicesIntersect = start <= gapEnd && end >= gapStart;
793 int gapLen = gapEnd - gapStart;
794 if (indicesIntersect && gapLen > 0) {
795 gapStart = kMax(gapStart, start);
796 gapEnd = kMin(gapEnd, end);
798 str = textNode->string()->substring(start, end - start);
801 // remove text in the gap
802 str->remove(gapStart - start - removed, gapLen);
808 box = box->nextTextBox();
812 // Replace the text between start and end with our pruned version.
814 replaceText(textNode, start, end - start, str);
817 // Assert that we are not going to delete all of the text in the node.
818 // If we were, that should have been done above with the call to
819 // removeNode and return.
820 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
821 deleteText(textNode, start, end - start);
827 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
829 if (start.isNull() || end.isNull())
832 if (RangeImpl::compareBoundaryPoints(start.node(), start.offset(), end.node(), end.offset()) >= 0)
835 NodeImpl *node = start.node();
837 NodeImpl *next = node->traverseNextNode();
839 if (node->isTextNode()) {
840 TextImpl *textNode = static_cast<TextImpl *>(node);
841 bool isStartNode = node == start.node();
842 bool isEndNode = node == end.node();
843 int startOffset = isStartNode ? start.offset() : 0;
844 int endOffset = isEndNode ? end.offset() : textNode->length();
845 deleteInsignificantText(textNode, startOffset, endOffset);
848 if (node == end.node())
854 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
856 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
857 deleteInsignificantText(pos, end);
860 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
862 document()->updateLayout();
864 RenderObject *renderer = node->renderer();
865 if (!renderer->isBlockFlow())
868 if (renderer->height() > 0)
871 int exceptionCode = 0;
872 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
873 ASSERT(exceptionCode == 0);
874 breakNode->setAttribute(ATTR_CLASS, blockPlaceholderClassString());
875 appendNode(breakNode, node);
878 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
880 document()->updateLayout();
882 RenderObject *renderer = node->renderer();
883 if (!renderer->isBlockFlow())
886 // This code will remove a block placeholder if it still is at the end
887 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
888 // Of course, a person who hand-edits an HTML file could move a
889 // placeholder around, but it seems OK to be unconcerned about that case.
890 NodeImpl *last = node->lastChild();
891 if (last && last->isHTMLElement()) {
892 ElementImpl *element = static_cast<ElementImpl *>(last);
893 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
901 //==========================================================================================
903 //------------------------------------------------------------------------------------------
906 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
907 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
909 ASSERT(m_appendChild);
910 m_appendChild->ref();
912 ASSERT(m_parentNode);
916 AppendNodeCommand::~AppendNodeCommand()
918 ASSERT(m_appendChild);
919 m_appendChild->deref();
921 ASSERT(m_parentNode);
922 m_parentNode->deref();
925 void AppendNodeCommand::doApply()
927 ASSERT(m_appendChild);
928 ASSERT(m_parentNode);
930 int exceptionCode = 0;
931 m_parentNode->appendChild(m_appendChild, exceptionCode);
932 ASSERT(exceptionCode == 0);
935 void AppendNodeCommand::doUnapply()
937 ASSERT(m_appendChild);
938 ASSERT(m_parentNode);
939 ASSERT(state() == Applied);
941 int exceptionCode = 0;
942 m_parentNode->removeChild(m_appendChild, exceptionCode);
943 ASSERT(exceptionCode == 0);
946 //------------------------------------------------------------------------------------------
949 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style)
950 : CompositeEditCommand(document), m_style(style)
956 ApplyStyleCommand::~ApplyStyleCommand()
962 void ApplyStyleCommand::doApply()
964 if (!endingSelection().isRange())
967 // adjust to the positions we want to use for applying style
968 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
969 Position end(endingSelection().end().upstream(StayInBlock));
971 // update document layout once before removing styles
972 // so that we avoid the expense of updating before each and every call
973 // to check a computed style
974 document()->updateLayout();
976 // Remove style from the selection.
977 // Use the upstream position of the start for removing style.
978 // This will ensure we remove all traces of the relevant styles from the selection
979 // and prevent us from adding redundant ones, as described in:
980 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
981 removeStyle(start.upstream(), end);
983 bool splitStart = splitTextAtStartIfNeeded(start, end);
985 start = endingSelection().start();
986 end = endingSelection().end();
988 splitTextAtEndIfNeeded(start, end);
989 start = endingSelection().start();
990 end = endingSelection().end();
992 // update document layout once before running the rest of the function
993 // so that we avoid the expense of updating before each and every call
994 // to check a computed style
995 document()->updateLayout();
997 if (start.node() == end.node()) {
998 // simple case...start and end are the same node
999 applyStyleIfNeeded(start.node(), end.node());
1002 NodeImpl *node = start.node();
1004 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1005 NodeImpl *runStart = node;
1007 NodeImpl *next = node->traverseNextNode();
1008 // Break if node is the end node, or if the next node does not fit in with
1009 // the current group.
1010 if (node == end.node() ||
1011 runStart->parentNode() != next->parentNode() ||
1012 (next->isHTMLElement() && next->id() != ID_BR) ||
1013 (next->renderer() && !next->renderer()->isInline()))
1017 // Now apply style to the run we found.
1018 applyStyleIfNeeded(runStart, node);
1020 if (node == end.node())
1022 node = node->traverseNextNode();
1027 //------------------------------------------------------------------------------------------
1028 // ApplyStyleCommand: style-removal helpers
1030 bool ApplyStyleCommand::isHTMLStyleNode(HTMLElementImpl *elem)
1032 for (QPtrListIterator<CSSProperty> it(*(style()->values())); it.current(); ++it) {
1033 CSSProperty *property = it.current();
1034 switch (property->id()) {
1035 case CSS_PROP_FONT_WEIGHT:
1036 if (elem->id() == ID_B)
1039 case CSS_PROP_FONT_STYLE:
1040 if (elem->id() == ID_I)
1049 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1051 // This node can be removed.
1052 // EDIT FIXME: This does not handle the case where the node
1053 // has attributes. But how often do people add attributes to <B> tags?
1054 // Not so often I think.
1056 removeNodePreservingChildren(elem);
1059 void ApplyStyleCommand::removeCSSStyle(HTMLElementImpl *elem)
1063 CSSStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1067 for (QPtrListIterator<CSSProperty> it(*(style()->values())); it.current(); ++it) {
1068 CSSProperty *property = it.current();
1069 if (decl->getPropertyCSSValue(property->id()))
1070 removeCSSProperty(decl, property->id());
1073 if (elem->id() == ID_SPAN) {
1074 // Check to see if the span is one we added to apply style.
1075 // If it is, and there are no more attributes on the span other than our
1076 // class marker, remove the span.
1077 if (decl->values()->count() == 0) {
1078 removeNodeAttribute(elem, ATTR_STYLE);
1079 NamedAttrMapImpl *map = elem->attributes();
1080 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1081 removeNodePreservingChildren(elem);
1086 void ApplyStyleCommand::removeStyle(const Position &start, const Position &end)
1088 ASSERT(start.isNotNull());
1089 ASSERT(end.isNotNull());
1090 ASSERT(start.node()->inDocument());
1091 ASSERT(end.node()->inDocument());
1093 NodeImpl *node = start.node();
1095 NodeImpl *next = node->traverseNextNode();
1096 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1097 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1098 if (isHTMLStyleNode(elem))
1099 removeHTMLStyleNode(elem);
1101 removeCSSStyle(elem);
1103 if (node == end.node())
1109 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1113 Position pos = Position(node, node->childNodeCount()).upstream();
1114 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1115 RangeImpl::compareBoundaryPoints(pos.node(), pos.offset(), end.node(), end.offset()) <= 0;
1118 //------------------------------------------------------------------------------------------
1119 // ApplyStyleCommand: style-application helpers
1122 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1124 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1125 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1126 TextImpl *text = static_cast<TextImpl *>(start.node());
1127 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1128 applyCommandToComposite(cmd);
1129 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1135 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1137 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1138 TextImpl *text = static_cast<TextImpl *>(end.node());
1139 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1140 EditCommandPtr cmd(impl);
1141 applyCommandToComposite(cmd);
1142 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1144 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1145 return impl->node()->previousSibling();
1150 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1156 NodeImpl *node = startNode;
1158 NodeImpl *next = node->traverseNextNode();
1159 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1161 appendNode(node, element);
1163 if (node == endNode)
1169 void ApplyStyleCommand::applyStyleIfNeeded(NodeImpl *startNode, NodeImpl *endNode)
1171 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1172 // Both functions do similar work, and the common parts could be factored out.
1174 StyleChange styleChange(style(), Position(startNode, 0));
1175 int exceptionCode = 0;
1177 if (styleChange.cssStyle().length() > 0) {
1178 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1179 ASSERT(exceptionCode == 0);
1180 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1181 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1182 insertNodeBefore(styleElement, startNode);
1183 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1186 if (styleChange.applyBold()) {
1187 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1188 ASSERT(exceptionCode == 0);
1189 insertNodeBefore(boldElement, startNode);
1190 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1193 if (styleChange.applyItalic()) {
1194 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1195 ASSERT(exceptionCode == 0);
1196 insertNodeBefore(italicElement, startNode);
1197 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1201 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1203 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1204 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1205 EditCommandPtr split(impl);
1207 pos = Position(impl->node(), 0);
1211 // EDIT FIXME: If modified to work with the internals of applying style,
1212 // this code can work to optimize cases where a style change is taking place on
1213 // a boundary between nodes where one of the nodes has the desired style. In other
1214 // words, it is possible for content to be merged into existing nodes rather than adding
1215 // additional markup.
1216 if (currentlyHasStyle(pos))
1220 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1221 NodeImpl *nextNode = pos.node()->traverseNextNode();
1223 Position next = Position(nextNode, 0);
1224 if (currentlyHasStyle(next))
1229 // try previous node
1230 if (pos.offset() <= pos.node()->caretMinOffset()) {
1231 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1233 Position prev = Position(prevNode, prevNode->maxOffset());
1234 if (currentlyHasStyle(prev))
1243 //------------------------------------------------------------------------------------------
1244 // DeleteSelectionCommand
1246 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1247 : CompositeEditCommand(document),
1248 m_hasSelectionToDelete(false),
1249 m_smartDelete(smartDelete),
1250 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1258 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1259 : CompositeEditCommand(document),
1260 m_hasSelectionToDelete(true),
1261 m_smartDelete(smartDelete),
1262 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1263 m_selectionToDelete(selection),
1271 void DeleteSelectionCommand::initializePositionData()
1273 Position start = startPositionForDelete();
1274 Position end = endPositionForDelete();
1276 m_upstreamStart = Position(start.upstream(StayInBlock));
1277 m_downstreamStart = Position(start.downstream(StayInBlock));
1278 m_upstreamEnd = Position(end.upstream(StayInBlock));
1279 m_downstreamEnd = Position(end.downstream(StayInBlock));
1281 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1282 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1283 m_trailingWhitespaceValid = true;
1285 debugPosition("m_upstreamStart ", m_upstreamStart);
1286 debugPosition("m_downstreamStart ", m_downstreamStart);
1287 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1288 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1289 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1290 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1292 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1293 m_startBlock->ref();
1294 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1297 m_startNode = m_upstreamStart.node();
1301 Position DeleteSelectionCommand::startPositionForDelete() const
1303 Position pos = m_selectionToDelete.start();
1304 ASSERT(pos.node()->inDocument());
1306 ElementImpl *rootElement = pos.node()->rootEditableElement();
1307 Position rootStart = Position(rootElement, 0);
1308 if (pos == VisiblePosition(rootStart).deepEquivalent())
1310 else if (m_smartDelete && pos.leadingWhitespacePosition().isNotNull())
1311 pos = VisiblePosition(pos).previous().deepEquivalent();
1315 Position DeleteSelectionCommand::endPositionForDelete() const
1317 Position pos = m_selectionToDelete.end();
1318 ASSERT(pos.node()->inDocument());
1320 ElementImpl *rootElement = pos.node()->rootEditableElement();
1321 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1322 if (pos == VisiblePosition(rootEnd).deepEquivalent())
1324 else if (m_smartDelete && pos.leadingWhitespacePosition().isNotNull())
1325 pos = VisiblePosition(pos).next().deepEquivalent();
1329 void DeleteSelectionCommand::saveTypingStyleState()
1331 // Figure out the typing style in effect before the delete is done.
1332 // FIXME: Improve typing style.
1333 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1334 CSSComputedStyleDeclarationImpl *computedStyle = m_downstreamStart.computedStyle();
1335 computedStyle->ref();
1336 m_typingStyle = computedStyle->copyInheritableProperties();
1337 m_typingStyle->ref();
1338 computedStyle->deref();
1341 bool DeleteSelectionCommand::canPerformSpecialCaseBRDelete()
1343 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1344 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1345 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1346 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1347 if (isBROnLineByItself) {
1348 removeNode(m_downstreamStart.node());
1349 m_endingPosition = m_upstreamStart;
1350 m_mergeBlocksAfterDelete = false;
1354 // Check for special-case where the selection contains only a BR right after a block ended.
1355 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1356 Position upstreamUpstreamStart = m_upstreamStart.upstream();
1357 bool startIsBRAfterBlock = downstreamEndIsBR && m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamUpstreamStart.node()->enclosingBlockFlowElement();
1358 if (startIsBRAfterBlock) {
1359 removeNode(m_downstreamEnd.node());
1360 m_endingPosition = upstreamUpstreamStart;
1361 m_mergeBlocksAfterDelete = false;
1365 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1366 // should not be done.
1367 if (upstreamStartIsBR && downstreamStartIsBR)
1368 m_mergeBlocksAfterDelete = false;
1373 void DeleteSelectionCommand::performGeneralDelete()
1375 int startOffset = m_upstreamStart.offset();
1376 if (startOffset >= m_startNode->caretMaxOffset()) {
1377 if (m_startNode->isTextNode()) {
1378 // Delete any insignificant text from this node.
1379 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1380 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1381 deleteText(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1383 // shift the start node to the next
1384 NodeImpl *old = m_startNode;
1385 m_startNode = old->traverseNextNode();
1391 if (m_startNode == m_downstreamEnd.node()) {
1392 // handle delete in one node
1393 if (!m_startNode->renderer() ||
1394 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1396 removeFullySelectedNode(m_startNode);
1398 else if (m_downstreamEnd.offset() - startOffset > 0) {
1399 // in a text node that needs to be trimmed
1400 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1401 deleteText(text, startOffset, m_downstreamEnd.offset() - startOffset);
1402 m_trailingWhitespaceValid = false;
1406 NodeImpl *node = m_startNode;
1408 if (startOffset > 0) {
1409 // in a text node that needs to be trimmed
1410 TextImpl *text = static_cast<TextImpl *>(node);
1411 deleteText(text, startOffset, text->length() - startOffset);
1412 node = node->traverseNextNode();
1415 // handle deleting all nodes that are completely selected
1416 while (node && node != m_downstreamEnd.node()) {
1417 if (!m_downstreamEnd.node()->isAncestor(node)) {
1418 NodeImpl *nextNode = node->traverseNextSibling();
1419 removeFullySelectedNode(node);
1423 NodeImpl *n = node->lastChild();
1424 while (n && n->lastChild())
1426 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1427 NodeImpl *nextNode = node->traverseNextSibling();
1428 removeFullySelectedNode(node);
1432 node = node->traverseNextNode();
1437 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1438 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1439 // need to delete whole node
1440 // we can get here if this is the last node in the block
1441 removeFullySelectedNode(m_downstreamEnd.node());
1442 m_trailingWhitespaceValid = false;
1445 // in a text node that needs to be trimmed
1446 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1447 if (m_downstreamEnd.offset() > 0) {
1448 deleteText(text, 0, m_downstreamEnd.offset());
1449 m_trailingWhitespaceValid = false;
1452 if (!m_downstreamEnd.node()->inDocument() && m_downstreamEnd.node()->inDocument())
1453 m_endingPosition = Position(m_downstreamEnd.node(), 0);
1458 void DeleteSelectionCommand::fixupWhitespace()
1460 document()->updateLayout();
1461 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1462 LOG(Editing, "replace leading");
1463 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1464 replaceText(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1466 else if (m_trailingWhitespace.isNotNull()) {
1467 if (m_trailingWhitespaceValid) {
1468 if (!m_trailingWhitespace.isRenderedCharacter()) {
1469 LOG(Editing, "replace trailing [valid]");
1470 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1471 replaceText(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1475 Position pos = m_endingPosition.downstream(StayInBlock);
1476 pos = Position(pos.node(), pos.offset() - 1);
1477 if (isWS(pos) && !pos.isRenderedCharacter()) {
1478 LOG(Editing, "replace trailing [invalid]");
1479 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1480 replaceText(textNode, pos.offset(), 1, nonBreakingSpaceString());
1481 // need to adjust ending position since the trailing position is not valid.
1482 m_endingPosition = pos;
1488 // This function moves nodes in the block containing startNode to dstBlock, starting
1489 // from startNode and proceeding to the end of the block. Nodes in the block containing
1490 // startNode that appear in document order before startNode are not moved.
1491 // This function is an important helper for deleting selections that cross block
1493 void DeleteSelectionCommand::moveNodesAfterNode()
1495 if (!m_mergeBlocksAfterDelete)
1498 if (m_endBlock == m_startBlock)
1501 NodeImpl *startNode = m_downstreamEnd.node();
1502 NodeImpl *dstNode = m_upstreamStart.node();
1504 if (!startNode->inDocument() || !dstNode->inDocument())
1507 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1508 if (isTableStructureNode(startBlock))
1509 // Do not move content between parts of a table
1512 // Now that we are about to add content, check to see if a placeholder element
1514 removeBlockPlaceholderIfNeeded(startBlock);
1516 NodeImpl *node = startNode == startBlock ? startBlock->firstChild() : startNode;
1519 NodeImpl *refNode = dstNode;
1520 while (node && node->isAncestor(startBlock)) {
1521 NodeImpl *moveNode = node;
1522 node = node->nextSibling();
1523 removeNode(moveNode);
1524 insertNodeAfter(moveNode, refNode);
1528 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1529 // to make the layout come out right. Consider this document:
1535 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1536 // move the contents of the div to the block containing 'One' and delete the div.
1537 // This will have the side effect of moving 'Three' on to the same line as 'One'
1538 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1539 // This may not be ideal, but it is better than nothing.
1540 document()->updateLayout();
1541 if (startBlock->renderer() && startBlock->renderer()->height() == 0) {
1542 removeNode(startBlock);
1543 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1544 int exceptionCode = 0;
1545 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1546 ASSERT(exceptionCode == 0);
1547 insertNodeAfter(breakNode, refNode);
1552 void DeleteSelectionCommand::calculateEndingPosition()
1554 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1557 m_endingPosition = m_upstreamStart;
1558 if (m_endingPosition.node()->inDocument())
1561 m_endingPosition = m_downstreamEnd;
1562 if (m_endingPosition.node()->inDocument())
1565 m_endingPosition = Position(m_startBlock, 0);
1566 if (m_endingPosition.node()->inDocument())
1569 m_endingPosition = Position(m_endBlock, 0);
1570 if (m_endingPosition.node()->inDocument())
1573 m_endingPosition = Position(document()->documentElement(), 0);
1576 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1578 // Compute the difference between the style before the delete and the style now
1579 // after the delete has been done. Set this style on the part, so other editing
1580 // commands being composed with this one will work, and also cache it on the command,
1581 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1583 // FIXME: Improve typing style.
1584 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1585 if (m_startNode == m_endingPosition.node())
1586 document()->part()->setTypingStyle(0);
1588 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1589 endingStyle.diff(m_typingStyle);
1590 if (!m_typingStyle->length()) {
1591 m_typingStyle->deref();
1594 document()->part()->setTypingStyle(m_typingStyle);
1595 setTypingStyle(m_typingStyle);
1599 void DeleteSelectionCommand::clearTransientState()
1601 m_selectionToDelete.clear();
1602 m_upstreamStart.clear();
1603 m_downstreamStart.clear();
1604 m_upstreamEnd.clear();
1605 m_downstreamEnd.clear();
1606 m_endingPosition.clear();
1607 m_leadingWhitespace.clear();
1608 m_trailingWhitespace.clear();
1611 m_startBlock->deref();
1615 m_endBlock->deref();
1619 m_startNode->deref();
1622 if (m_typingStyle) {
1623 m_typingStyle->deref();
1628 void DeleteSelectionCommand::doApply()
1630 // If selection has not been set to a custom selection when the command was created,
1631 // use the current ending selection.
1632 if (!m_hasSelectionToDelete)
1633 m_selectionToDelete = endingSelection();
1635 if (!m_selectionToDelete.isRange())
1638 initializePositionData();
1640 if (!m_startBlock || !m_endBlock) {
1641 // Can't figure out what blocks we're in. This can happen if
1642 // the document structure is not what we are expecting, like if
1643 // the document has no body element, or if the editable block
1644 // has been changed to display: inline. Some day it might
1645 // be nice to be able to deal with this, but for now, bail.
1646 clearTransientState();
1650 // Delete any text that may hinder our ability to fixup whitespace after the detele
1651 deleteInsignificantTextDownstream(m_trailingWhitespace);
1653 saveTypingStyleState();
1655 if (!canPerformSpecialCaseBRDelete())
1656 performGeneralDelete();
1658 // Do block merge if start and end of selection are in different blocks.
1659 moveNodesAfterNode();
1661 calculateEndingPosition();
1664 // If the delete emptied a block, add in a placeholder so the block does not
1665 // seem to disappear.
1666 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1667 calculateTypingStyleAfterDelete();
1668 setEndingSelection(m_endingPosition);
1669 debugPosition("endingPosition ", m_endingPosition);
1670 clearTransientState();
1673 bool DeleteSelectionCommand::preservesTypingStyle() const
1678 //------------------------------------------------------------------------------------------
1679 // DeleteTextCommand
1681 DeleteTextCommand::DeleteTextCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1682 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1685 ASSERT(m_offset >= 0);
1686 ASSERT(m_offset < (long)m_node->length());
1687 ASSERT(m_count >= 0);
1692 DeleteTextCommand::~DeleteTextCommand()
1698 void DeleteTextCommand::doApply()
1702 int exceptionCode = 0;
1703 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1704 ASSERT(exceptionCode == 0);
1706 m_node->deleteData(m_offset, m_count, exceptionCode);
1707 ASSERT(exceptionCode == 0);
1710 void DeleteTextCommand::doUnapply()
1713 ASSERT(!m_text.isEmpty());
1715 int exceptionCode = 0;
1716 m_node->insertData(m_offset, m_text, exceptionCode);
1717 ASSERT(exceptionCode == 0);
1720 //------------------------------------------------------------------------------------------
1721 // InputNewlineCommand
1723 InputNewlineCommand::InputNewlineCommand(DocumentImpl *document)
1724 : CompositeEditCommand(document)
1728 void InputNewlineCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
1730 // Insert the BR after the caret position. In the case the
1731 // position is a block, do an append. We don't want to insert
1732 // the BR *after* the block.
1733 Position upstream(pos.upstream(StayInBlock));
1734 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1735 if (cb == pos.node())
1736 appendNode(node, cb);
1738 insertNodeAfter(node, pos.node());
1741 void InputNewlineCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
1743 // Insert the BR after the caret position. In the case the
1744 // position is a block, do an append. We don't want to insert
1745 // the BR *before* the block.
1746 Position upstream(pos.upstream(StayInBlock));
1747 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1748 if (cb == pos.node())
1749 appendNode(node, cb);
1751 insertNodeBefore(node, pos.node());
1754 void InputNewlineCommand::doApply()
1757 Selection selection = endingSelection();
1759 int exceptionCode = 0;
1760 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1761 ASSERT(exceptionCode == 0);
1763 NodeImpl *nodeToInsert = breakNode;
1765 // Handle the case where there is a typing style.
1766 // FIXME: Improve typing style.
1767 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1768 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
1769 if (typingStyle && typingStyle->length() > 0)
1770 nodeToInsert = applyTypingStyle(breakNode);
1772 Position pos(selection.start().upstream(StayInBlock));
1773 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
1774 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
1775 bool atEndOfBlock = VisiblePosition(pos).isLastInBlock();
1778 LOG(Editing, "input newline case 1");
1779 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
1780 // This makes the "real" BR we want to insert appear in the rendering without any
1781 // significant side effects (and no real worries either since you can't arrow past
1783 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
1784 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
1785 insertNodeBefore(nodeToInsert, pos.node());
1788 NodeImpl *next = pos.node()->traverseNextNode();
1789 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
1790 insertNodeAfterPosition(nodeToInsert, pos);
1791 if (hasTrailingBR) {
1792 setEndingSelection(Position(next, 0));
1795 // Insert an "extra" BR at the end of the block.
1796 ElementImpl *extraBreakNode = document()->createHTMLElement("BR", exceptionCode);
1797 ASSERT(exceptionCode == 0);
1798 insertNodeAfter(extraBreakNode, nodeToInsert);
1799 setEndingSelection(Position(extraBreakNode, 0));
1804 LOG(Editing, "input newline case 2");
1805 // Insert node before downstream position, and place caret there as well.
1806 Position endingPosition = pos.downstream(StayInBlock);
1807 insertNodeBeforePosition(nodeToInsert, endingPosition);
1808 setEndingSelection(endingPosition);
1811 LOG(Editing, "input newline case 3");
1812 // Insert BR after this node. Place caret in the position that is downstream
1813 // of the current position, reckoned before inserting the BR in between.
1814 Position endingPosition = pos.downstream(StayInBlock);
1815 insertNodeAfterPosition(nodeToInsert, pos);
1816 setEndingSelection(endingPosition);
1819 // Split a text node
1820 LOG(Editing, "input newline case 4");
1821 ASSERT(pos.node()->isTextNode());
1824 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1825 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
1826 deleteText(textNode, 0, pos.offset());
1827 insertNodeBefore(textBeforeNode, textNode);
1828 insertNodeBefore(nodeToInsert, textNode);
1829 Position endingPosition = Position(textNode, 0);
1831 // Handle whitespace that occurs after the split
1832 document()->updateLayout();
1833 if (!endingPosition.isRenderedCharacter()) {
1834 // Clear out all whitespace and insert one non-breaking space
1835 deleteInsignificantTextDownstream(endingPosition);
1836 insertText(textNode, 0, nonBreakingSpaceString());
1839 setEndingSelection(endingPosition);
1843 //------------------------------------------------------------------------------------------
1844 // InputNewlineInQuotedContentCommand
1846 InputNewlineInQuotedContentCommand::InputNewlineInQuotedContentCommand(DocumentImpl *document)
1847 : CompositeEditCommand(document)
1849 ancestors.setAutoDelete(true);
1850 clonedNodes.setAutoDelete(true);
1853 InputNewlineInQuotedContentCommand::~InputNewlineInQuotedContentCommand()
1856 m_breakNode->deref();
1859 bool InputNewlineInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
1861 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
1864 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
1867 bool InputNewlineInQuotedContentCommand::isLastVisiblePositionInBlockquote(const VisiblePosition &pos, const NodeImpl *blockquote) const
1872 VisiblePosition next = pos.next();
1873 return next.isNull() || !next.deepEquivalent().node()->isAncestor(blockquote);
1876 void InputNewlineInQuotedContentCommand::doApply()
1878 Selection selection = endingSelection();
1879 if (selection.isNone())
1882 // Delete the current selection.
1883 Position pos = selection.start();
1884 if (selection.isRange()) {
1885 deleteSelection(false, false);
1886 pos = endingSelection().start().upstream();
1889 // Find the top-most blockquote from the start.
1890 NodeImpl *startNode = pos.node();
1891 NodeImpl *topBlockquote = 0;
1892 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
1893 if (isMailBlockquote(n))
1896 if (!topBlockquote || !topBlockquote->parentNode())
1899 // Build up list of ancestors in between the start node and the top blockquote.
1900 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
1901 ancestors.prepend(n);
1903 // Insert a break after the top blockquote.
1904 int exceptionCode = 0;
1905 m_breakNode = document()->createHTMLElement("BR", exceptionCode);
1907 ASSERT(exceptionCode == 0);
1908 insertNodeAfter(m_breakNode, topBlockquote);
1910 if (!isLastVisiblePositionInBlockquote(VisiblePosition(pos), topBlockquote)) {
1911 // Split at pos if in the middle of a text node.
1912 if (startNode->isTextNode()) {
1913 TextImpl *textNode = static_cast<TextImpl *>(startNode);
1914 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
1915 if (pos.offset() > 0 && !atEnd) {
1916 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
1917 EditCommandPtr cmd(splitCommand);
1918 applyCommandToComposite(cmd);
1919 startNode = splitCommand->node();
1920 pos = Position(startNode, 0);
1923 startNode = startNode->traverseNextNode();
1927 else if (pos.offset() > 0) {
1928 startNode = startNode->traverseNextNode();
1932 // Insert a clone of the top blockquote after the break.
1933 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
1934 clonedNodes.append(clonedBlockquote);
1935 insertNodeAfter(clonedBlockquote, m_breakNode);
1937 // Make clones of ancestors in between the start node and the top blockquote.
1938 NodeImpl *parent = clonedBlockquote;
1939 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
1940 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
1941 clonedNodes.append(child);
1942 appendNode(child, parent);
1946 // Move the start node and the siblings of the start node.
1947 NodeImpl *n = startNode;
1948 bool startIsBR = n->id() == ID_BR;
1950 n = n->nextSibling();
1952 NodeImpl *next = n->nextSibling();
1954 appendNode(n, parent);
1958 // Move everything after the start node.
1959 NodeImpl *leftParent = ancestors.last();
1963 leftParent = topBlockquote;
1964 ElementImpl *b = document()->createHTMLElement("BR", exceptionCode);
1965 clonedNodes.append(b);
1966 ASSERT(exceptionCode == 0);
1967 appendNode(b, leftParent);
1970 leftParent = ancestors.last();
1971 while (leftParent && leftParent != topBlockquote) {
1972 parent = parent->parentNode();
1973 NodeImpl *n = leftParent->nextSibling();
1975 NodeImpl *next = n->nextSibling();
1977 appendNode(n, parent);
1980 leftParent = leftParent->parentNode();
1984 // Put the selection right before the break.
1985 setEndingSelection(Position(m_breakNode, 0));
1988 //------------------------------------------------------------------------------------------
1991 InputTextCommand::InputTextCommand(DocumentImpl *document)
1992 : CompositeEditCommand(document), m_charactersAdded(0)
1996 void InputTextCommand::doApply()
2000 void InputTextCommand::deleteCharacter()
2002 ASSERT(state() == Applied);
2004 Selection selection = endingSelection();
2006 if (!selection.start().node()->isTextNode())
2009 int exceptionCode = 0;
2010 int offset = selection.start().offset() - 1;
2011 if (offset >= selection.start().node()->caretMinOffset()) {
2012 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2013 textNode->deleteData(offset, 1, exceptionCode);
2014 ASSERT(exceptionCode == 0);
2015 selection = Selection(Position(textNode, offset));
2016 setEndingSelection(selection);
2017 m_charactersAdded--;
2021 Position InputTextCommand::prepareForTextInsertion(bool adjustDownstream)
2023 // Prepare for text input by looking at the current position.
2024 // It may be necessary to insert a text node to receive characters.
2025 Selection selection = endingSelection();
2026 ASSERT(selection.isCaret());
2028 Position pos = selection.start();
2029 if (adjustDownstream)
2030 pos = pos.downstream(StayInBlock);
2032 pos = pos.upstream(StayInBlock);
2034 if (!pos.node()->isTextNode()) {
2035 NodeImpl *textNode = document()->createEditingTextNode("");
2036 NodeImpl *nodeToInsert = textNode;
2038 // Handle the case where there is a typing style.
2039 // FIXME: Improve typing style.
2040 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2041 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2042 if (typingStyle && typingStyle->length() > 0)
2043 nodeToInsert = applyTypingStyle(textNode);
2045 // Now insert the node in the right place
2046 if (pos.node()->isEditableBlock()) {
2047 LOG(Editing, "prepareForTextInsertion case 1");
2048 appendNode(nodeToInsert, pos.node());
2050 else if (pos.node()->caretMinOffset() == pos.offset()) {
2051 LOG(Editing, "prepareForTextInsertion case 2");
2052 insertNodeBefore(nodeToInsert, pos.node());
2054 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2055 LOG(Editing, "prepareForTextInsertion case 3");
2056 insertNodeAfter(nodeToInsert, pos.node());
2059 ASSERT_NOT_REACHED();
2061 pos = Position(textNode, 0);
2064 // Handle the case where there is a typing style.
2065 // FIXME: Improve typing style.
2066 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2067 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2068 if (typingStyle && typingStyle->length() > 0) {
2069 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2070 // Need to split current text node in order to insert a span.
2071 TextImpl *text = static_cast<TextImpl *>(pos.node());
2072 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2073 EditCommandPtr cmd(impl);
2074 applyCommandToComposite(cmd);
2075 setEndingSelection(Position(impl->node(), 0));
2078 TextImpl *editingTextNode = document()->createEditingTextNode("");
2079 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2080 if (node->isBlockFlow())
2081 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2083 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2084 pos = Position(editingTextNode, 0);
2090 void InputTextCommand::input(const DOMString &text, bool selectInsertedText)
2092 Selection selection = endingSelection();
2093 bool adjustDownstream = selection.start().downstream(StayInBlock).isFirstRenderedPositionOnLine();
2095 // Delete the current selection, or collapse whitespace, as needed
2096 if (selection.isRange())
2099 // Delete any insignificant text that could get in the way of whitespace turning
2100 // out correctly after the insertion.
2101 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2103 // Make sure the document is set up to receive text
2104 Position pos = prepareForTextInsertion(adjustDownstream);
2106 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2107 long offset = pos.offset();
2109 // Now that we are about to add content, check to see if a placeholder element
2111 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2113 // These are temporary implementations for inserting adjoining spaces
2114 // into a document. We are working on a CSS-related whitespace solution
2115 // that will replace this some day. We hope.
2117 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2118 // although the number of spaces varies (we choose four spaces).
2119 // Note that there is no attempt to make this work like a real tab stop, it is merely
2120 // a set number of spaces. This also seems to be the HTML editing convention.
2121 for (int i = 0; i < spacesPerTab; i++) {
2122 insertSpace(textNode, offset);
2123 document()->updateLayout();
2125 if (selectInsertedText)
2126 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2128 setEndingSelection(Position(textNode, offset + spacesPerTab));
2129 m_charactersAdded += spacesPerTab;
2131 else if (isWS(text)) {
2132 insertSpace(textNode, offset);
2133 if (selectInsertedText)
2134 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2136 setEndingSelection(Position(textNode, offset + 1));
2137 m_charactersAdded++;
2140 const DOMString &existingText = textNode->data();
2141 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2142 // DOM looks like this:
2143 // character nbsp caret
2144 // As we are about to insert a non-whitespace character at the caret
2145 // convert the nbsp to a regular space.
2146 // EDIT FIXME: This needs to be improved some day to convert back only
2147 // those nbsp's added by the editor to make rendering come out right.
2148 replaceText(textNode, offset - 1, 1, " ");
2150 insertText(textNode, offset, text);
2151 if (selectInsertedText)
2152 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2154 setEndingSelection(Position(textNode, offset + text.length()));
2155 m_charactersAdded += text.length();
2159 void InputTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2163 DOMString text(textNode->data());
2165 // count up all spaces and newlines in front of the caret
2166 // delete all collapsed ones
2167 // this will work out OK since the offset we have been passed has been upstream-ized
2169 for (unsigned int i = offset; i < text.length(); i++) {
2176 // By checking the character at the downstream position, we can
2177 // check if there is a rendered WS at the caret
2178 Position pos(textNode, offset);
2179 Position downstream = pos.downstream();
2180 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2181 count--; // leave this WS in
2183 deleteText(textNode, offset, count);
2186 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2187 // insert a "regular" space
2188 insertText(textNode, offset, " ");
2192 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2193 // DOM looks like this:
2195 // insert a space between the two nbsps
2196 insertText(textNode, offset - 1, " ");
2201 insertText(textNode, offset, nonBreakingSpaceString());
2204 bool InputTextCommand::isInputTextCommand() const
2209 //------------------------------------------------------------------------------------------
2210 // InsertNodeBeforeCommand
2212 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2213 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2215 ASSERT(m_insertChild);
2216 m_insertChild->ref();
2222 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2224 ASSERT(m_insertChild);
2225 m_insertChild->deref();
2228 m_refChild->deref();
2231 void InsertNodeBeforeCommand::doApply()
2233 ASSERT(m_insertChild);
2235 ASSERT(m_refChild->parentNode());
2237 int exceptionCode = 0;
2238 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2239 ASSERT(exceptionCode == 0);
2242 void InsertNodeBeforeCommand::doUnapply()
2244 ASSERT(m_insertChild);
2246 ASSERT(m_refChild->parentNode());
2248 int exceptionCode = 0;
2249 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2250 ASSERT(exceptionCode == 0);
2253 //------------------------------------------------------------------------------------------
2254 // InsertTextCommand
2256 InsertTextCommand::InsertTextCommand(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
2257 : EditCommand(document), m_node(node), m_offset(offset)
2260 ASSERT(m_offset >= 0);
2261 ASSERT(!text.isEmpty());
2264 m_text = text.copy(); // make a copy to ensure that the string never changes
2267 InsertTextCommand::~InsertTextCommand()
2273 void InsertTextCommand::doApply()
2276 ASSERT(m_offset >= 0);
2277 ASSERT(!m_text.isEmpty());
2279 int exceptionCode = 0;
2280 m_node->insertData(m_offset, m_text, exceptionCode);
2281 ASSERT(exceptionCode == 0);
2284 void InsertTextCommand::doUnapply()
2287 ASSERT(m_offset >= 0);
2288 ASSERT(!m_text.isEmpty());
2290 int exceptionCode = 0;
2291 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
2292 ASSERT(exceptionCode == 0);
2295 //------------------------------------------------------------------------------------------
2296 // JoinTextNodesCommand
2298 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2299 : EditCommand(document), m_text1(text1), m_text2(text2)
2303 ASSERT(m_text1->nextSibling() == m_text2);
2304 ASSERT(m_text1->length() > 0);
2305 ASSERT(m_text2->length() > 0);
2311 JoinTextNodesCommand::~JoinTextNodesCommand()
2319 void JoinTextNodesCommand::doApply()
2323 ASSERT(m_text1->nextSibling() == m_text2);
2325 int exceptionCode = 0;
2326 m_text2->insertData(0, m_text1->data(), exceptionCode);
2327 ASSERT(exceptionCode == 0);
2329 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2330 ASSERT(exceptionCode == 0);
2332 m_offset = m_text1->length();
2335 void JoinTextNodesCommand::doUnapply()
2338 ASSERT(m_offset > 0);
2340 int exceptionCode = 0;
2342 m_text2->deleteData(0, m_offset, exceptionCode);
2343 ASSERT(exceptionCode == 0);
2345 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2346 ASSERT(exceptionCode == 0);
2348 ASSERT(m_text2->previousSibling()->isTextNode());
2349 ASSERT(m_text2->previousSibling() == m_text1);
2352 //------------------------------------------------------------------------------------------
2353 // ReplaceSelectionCommand
2355 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
2356 : CompositeEditCommand(document), m_fragment(fragment), m_selectReplacement(selectReplacement), m_smartReplace(smartReplace)
2362 ReplaceSelectionCommand::~ReplaceSelectionCommand()
2365 m_fragment->deref();
2368 void ReplaceSelectionCommand::doApply()
2370 NodeImpl *firstChild = m_fragment->firstChild();
2371 NodeImpl *lastChild = m_fragment->lastChild();
2373 Selection selection = endingSelection();
2375 // Delete the current selection, or collapse whitespace, as needed
2376 if (selection.isRange())
2379 // This command does not use any typing style that is set as a residual effect of
2381 // FIXME: Improve typing style.
2382 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2383 document()->part()->clearTypingStyle();
2386 selection = endingSelection();
2387 ASSERT(selection.isCaret());
2389 // Now that we are about to add content, check to see if a placeholder element
2391 Position pos = selection.start();
2392 NodeImpl *block = pos.node()->enclosingBlockFlowElement();
2393 if (removeBlockPlaceholderIfNeeded(block)) {
2394 pos = Position(block, 0);
2397 bool addLeadingSpace = false;
2398 bool addTrailingSpace = false;
2399 if (m_smartReplace) {
2400 addLeadingSpace = pos.leadingWhitespacePosition().isNull();
2401 addTrailingSpace = pos.trailingWhitespacePosition().isNull();
2405 // Pasting something that didn't parse or was empty.
2407 } else if (firstChild == lastChild && firstChild->isTextNode()) {
2408 // FIXME: HTML fragment case needs to be improved to the point
2409 // where we can remove this separate case.
2411 // Simple text paste. Treat as if the text were typed.
2412 Position upstreamStart(pos.upstream(StayInBlock));
2413 DOMString text = static_cast<TextImpl *>(firstChild)->data();
2414 if (addLeadingSpace) {
2417 if (addTrailingSpace) {
2420 inputText(text, m_selectReplacement);
2423 // HTML fragment paste.
2425 // FIXME: Add leading and trailing spaces to the fragment?
2426 // Or just insert them as we insert it?
2428 NodeImpl *beforeNode = firstChild;
2429 NodeImpl *node = firstChild->nextSibling();
2431 insertNodeAt(firstChild, pos.node(), pos.offset());
2433 // Insert the nodes from the fragment
2435 NodeImpl *next = node->nextSibling();
2436 insertNodeAfter(node, beforeNode);
2442 // Find the last leaf.
2443 NodeImpl *lastLeaf = lastChild;
2445 NodeImpl *nextChild = lastLeaf->lastChild();
2448 lastLeaf = nextChild;
2451 // Find the first leaf.
2452 NodeImpl *firstLeaf = firstChild;
2454 NodeImpl *nextChild = firstLeaf->firstChild();
2457 firstLeaf = nextChild;
2460 Selection replacementSelection(Position(firstLeaf, firstLeaf->caretMinOffset()), Position(lastLeaf, lastLeaf->caretMaxOffset()));
2461 if (m_selectReplacement) {
2462 // Select what was inserted.
2463 setEndingSelection(replacementSelection);
2466 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
2467 selection = Selection(Position(lastLeaf, lastLeaf->caretMaxOffset()));
2468 setEndingSelection(selection);
2473 //------------------------------------------------------------------------------------------
2474 // MoveSelectionCommand
2476 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2477 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2483 MoveSelectionCommand::~MoveSelectionCommand()
2486 m_fragment->deref();
2489 void MoveSelectionCommand::doApply()
2491 Selection selection = endingSelection();
2492 ASSERT(selection.isRange());
2494 // Update the position otherwise it may become invalid after the selection is deleted.
2495 NodeImpl *positionNode = m_position.node();
2496 long positionOffset = m_position.offset();
2497 Position selectionEnd = selection.end();
2498 long selectionEndOffset = selectionEnd.offset();
2499 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2500 positionOffset -= selectionEndOffset;
2501 Position selectionStart = selection.start();
2502 if (selectionStart.node() == positionNode) {
2503 positionOffset += selectionStart.offset();
2507 deleteSelection(m_smartMove);
2509 setEndingSelection(Position(positionNode, positionOffset));
2510 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2511 applyCommandToComposite(cmd);
2514 //------------------------------------------------------------------------------------------
2515 // RemoveCSSPropertyCommand
2517 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2518 : EditCommand(document), m_decl(decl), m_property(property), m_important(false)
2524 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
2530 void RemoveCSSPropertyCommand::doApply()
2534 m_oldValue = m_decl->getPropertyValue(m_property);
2535 ASSERT(!m_oldValue.isNull());
2537 m_important = m_decl->getPropertyPriority(m_property);
2538 m_decl->removeProperty(m_property);
2541 void RemoveCSSPropertyCommand::doUnapply()
2544 ASSERT(!m_oldValue.isNull());
2546 m_decl->setProperty(m_property, m_oldValue, m_important);
2549 //------------------------------------------------------------------------------------------
2550 // RemoveNodeAttributeCommand
2552 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
2553 : EditCommand(document), m_element(element), m_attribute(attribute)
2559 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
2565 void RemoveNodeAttributeCommand::doApply()
2569 m_oldValue = m_element->getAttribute(m_attribute);
2570 ASSERT(!m_oldValue.isNull());
2572 int exceptionCode = 0;
2573 m_element->removeAttribute(m_attribute, exceptionCode);
2574 ASSERT(exceptionCode == 0);
2577 void RemoveNodeAttributeCommand::doUnapply()
2580 ASSERT(!m_oldValue.isNull());
2582 int exceptionCode = 0;
2583 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2584 ASSERT(exceptionCode == 0);
2587 //------------------------------------------------------------------------------------------
2588 // RemoveNodeCommand
2590 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
2591 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
2593 ASSERT(m_removeChild);
2594 m_removeChild->ref();
2596 m_parent = m_removeChild->parentNode();
2600 m_refChild = m_removeChild->nextSibling();
2605 RemoveNodeCommand::~RemoveNodeCommand()
2610 ASSERT(m_removeChild);
2611 m_removeChild->deref();
2614 m_refChild->deref();
2617 void RemoveNodeCommand::doApply()
2620 ASSERT(m_removeChild);
2622 int exceptionCode = 0;
2623 m_parent->removeChild(m_removeChild, exceptionCode);
2624 ASSERT(exceptionCode == 0);
2627 void RemoveNodeCommand::doUnapply()
2630 ASSERT(m_removeChild);
2632 int exceptionCode = 0;
2633 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
2634 ASSERT(exceptionCode == 0);
2637 //------------------------------------------------------------------------------------------
2638 // RemoveNodePreservingChildrenCommand
2640 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
2641 : CompositeEditCommand(document), m_node(node)
2647 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
2653 void RemoveNodePreservingChildrenCommand::doApply()
2655 while (NodeImpl* curr = node()->firstChild()) {
2657 insertNodeBefore(curr, node());
2662 //------------------------------------------------------------------------------------------
2663 // SetNodeAttributeCommand
2665 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
2666 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
2670 ASSERT(!m_value.isNull());
2673 SetNodeAttributeCommand::~SetNodeAttributeCommand()
2679 void SetNodeAttributeCommand::doApply()
2682 ASSERT(!m_value.isNull());
2684 int exceptionCode = 0;
2685 m_oldValue = m_element->getAttribute(m_attribute);
2686 m_element->setAttribute(m_attribute, m_value.implementation(), exceptionCode);
2687 ASSERT(exceptionCode == 0);
2690 void SetNodeAttributeCommand::doUnapply()
2693 ASSERT(!m_oldValue.isNull());
2695 int exceptionCode = 0;
2696 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2697 ASSERT(exceptionCode == 0);
2700 //------------------------------------------------------------------------------------------
2701 // SplitTextNodeCommand
2703 SplitTextNodeCommand::SplitTextNodeCommand(DocumentImpl *document, TextImpl *text, long offset)
2704 : EditCommand(document), m_text1(0), m_text2(text), m_offset(offset)
2707 ASSERT(m_text2->length() > 0);
2712 SplitTextNodeCommand::~SplitTextNodeCommand()
2721 void SplitTextNodeCommand::doApply()
2724 ASSERT(m_offset > 0);
2726 int exceptionCode = 0;
2728 // EDIT FIXME: This should use better smarts for figuring out which portion
2729 // of the split to copy (based on their comparitive sizes). We should also
2730 // just use the DOM's splitText function.
2733 // create only if needed.
2734 // if reapplying, this object will already exist.
2735 m_text1 = document()->createTextNode(m_text2->substringData(0, m_offset, exceptionCode));
2736 ASSERT(exceptionCode == 0);
2741 m_text2->deleteData(0, m_offset, exceptionCode);
2742 ASSERT(exceptionCode == 0);
2744 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2745 ASSERT(exceptionCode == 0);
2747 ASSERT(m_text2->previousSibling()->isTextNode());
2748 ASSERT(m_text2->previousSibling() == m_text1);
2751 void SplitTextNodeCommand::doUnapply()
2756 ASSERT(m_text1->nextSibling() == m_text2);
2758 int exceptionCode = 0;
2759 m_text2->insertData(0, m_text1->data(), exceptionCode);
2760 ASSERT(exceptionCode == 0);
2762 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2763 ASSERT(exceptionCode == 0);
2765 m_offset = m_text1->length();
2768 //------------------------------------------------------------------------------------------
2771 TypingCommand::TypingCommand(DocumentImpl *document, ETypingCommand commandType, const DOMString &textToInsert, bool selectInsertedText)
2772 : CompositeEditCommand(document), m_commandType(commandType), m_textToInsert(textToInsert), m_openForMoreTyping(true), m_applyEditing(false), m_selectInsertedText(selectInsertedText)
2776 void TypingCommand::deleteKeyPressed(DocumentImpl *document)
2780 KHTMLPart *part = document->part();
2783 EditCommandPtr lastEditCommand = part->lastEditCommand();
2784 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2785 static_cast<TypingCommand *>(lastEditCommand.get())->deleteKeyPressed();
2788 EditCommandPtr cmd(new TypingCommand(document, DeleteKey));
2793 void TypingCommand::insertText(DocumentImpl *document, const DOMString &text, bool selectInsertedText)
2797 KHTMLPart *part = document->part();
2800 EditCommandPtr lastEditCommand = part->lastEditCommand();
2801 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2802 static_cast<TypingCommand *>(lastEditCommand.get())->insertText(text, selectInsertedText);
2805 EditCommandPtr cmd(new TypingCommand(document, InsertText, text, selectInsertedText));
2810 void TypingCommand::insertNewline(DocumentImpl *document)
2814 KHTMLPart *part = document->part();
2817 EditCommandPtr lastEditCommand = part->lastEditCommand();
2818 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2819 static_cast<TypingCommand *>(lastEditCommand.get())->insertNewline();
2822 EditCommandPtr cmd(new TypingCommand(document, InsertNewline));
2827 void TypingCommand::insertNewlineInQuotedContent(DocumentImpl *document)
2831 KHTMLPart *part = document->part();
2834 EditCommandPtr lastEditCommand = part->lastEditCommand();
2835 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2836 static_cast<TypingCommand *>(lastEditCommand.get())->insertNewlineInQuotedContent();
2839 EditCommandPtr cmd(new TypingCommand(document, InsertNewlineInQuotedContent));
2844 bool TypingCommand::isOpenForMoreTypingCommand(const EditCommandPtr &cmd)
2846 return cmd.isTypingCommand() &&
2847 static_cast<const TypingCommand *>(cmd.get())->openForMoreTyping();
2850 void TypingCommand::closeTyping(const EditCommandPtr &cmd)
2852 if (isOpenForMoreTypingCommand(cmd))
2853 static_cast<TypingCommand *>(cmd.get())->closeTyping();
2856 void TypingCommand::doApply()
2858 if (endingSelection().isNone())
2861 switch (m_commandType) {
2866 insertText(m_textToInsert, m_selectInsertedText);
2871 case InsertNewlineInQuotedContent:
2872 insertNewlineInQuotedContent();
2876 ASSERT_NOT_REACHED();
2879 void TypingCommand::markMisspellingsAfterTyping()
2881 // Take a look at the selection that results after typing and determine whether we need to spellcheck.
2882 // Since the word containing the current selection is never marked, this does a check to
2883 // see if typing made a new word that is not in the current selection. Basically, you
2884 // get this by being at the end of a word and typing a space.
2885 VisiblePosition start(endingSelection().start());
2886 VisiblePosition previous = start.previous();
2887 if (previous.isNotNull()) {
2888 VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
2889 VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
2891 KWQ(document()->part())->markMisspellingsInAdjacentWords(p1);
2895 void TypingCommand::typingAddedToOpenCommand()
2897 markMisspellingsAfterTyping();
2898 // Do not apply editing to the part on the first time through.
2899 // The part will get told in the same way as all other commands.
2900 // But since this command stays open and is used for additional typing,
2901 // we need to tell the part here as other commands are added.
2902 if (m_applyEditing) {
2903 EditCommandPtr cmd(this);
2904 document()->part()->appliedEditing(cmd);
2906 m_applyEditing = true;
2909 void TypingCommand::insertText(const DOMString &text, bool selectInsertedText)
2911 // FIXME: Improve typing style.
2912 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2913 if (document()->part()->typingStyle() || m_cmds.count() == 0) {
2914 InputTextCommand *impl = new InputTextCommand(document());
2915 EditCommandPtr cmd(impl);
2916 applyCommandToComposite(cmd);
2917 impl->input(text, selectInsertedText);
2920 EditCommandPtr lastCommand = m_cmds.last();
2921 if (lastCommand.isInputTextCommand()) {
2922 InputTextCommand *impl = static_cast<InputTextCommand *>(lastCommand.get());
2923 impl->input(text, selectInsertedText);
2926 InputTextCommand *impl = new InputTextCommand(document());
2927 EditCommandPtr cmd(impl);
2928 applyCommandToComposite(cmd);
2929 impl->input(text, selectInsertedText);
2932 typingAddedToOpenCommand();
2935 void TypingCommand::insertNewline()
2937 EditCommandPtr cmd(new InputNewlineCommand(document()));
2938 applyCommandToComposite(cmd);
2939 typingAddedToOpenCommand();
2942 void TypingCommand::insertNewlineInQuotedContent()
2944 EditCommandPtr cmd(new InputNewlineInQuotedContentCommand(document()));
2945 applyCommandToComposite(cmd);
2946 typingAddedToOpenCommand();
2949 void TypingCommand::issueCommandForDeleteKey()
2951 Selection selectionToDelete;
2953 switch (endingSelection().state()) {
2954 case Selection::RANGE:
2955 selectionToDelete = endingSelection();
2957 case Selection::CARET: {
2958 // Handle delete at beginning-of-block case.
2959 // Do nothing in the case that the caret is at the start of a
2960 // root editable element or at the start of a document.
2961 Position pos(endingSelection().start());
2962 Position start = VisiblePosition(pos).previous().deepEquivalent();
2963 Position end = VisiblePosition(pos).deepEquivalent();
2964 if (start.isNotNull() && end.isNotNull() && start.node()->rootEditableElement() == end.node()->rootEditableElement())
2965 selectionToDelete = Selection(start, end);
2968 case Selection::NONE:
2969 ASSERT_NOT_REACHED();
2973 if (selectionToDelete.isCaretOrRange()) {
2974 deleteSelection(selectionToDelete);
2975 typingAddedToOpenCommand();
2979 void TypingCommand::deleteKeyPressed()
2981 // EDIT FIXME: The ifdef'ed out code below should be re-enabled.
2982 // In order for this to happen, the deleteCharacter case
2983 // needs work. Specifically, the caret-positioning code
2984 // and whitespace-handling code in DeleteSelectionCommand::doApply()
2985 // needs to be factored out so it can be used again here.
2986 // Until that work is done, issueCommandForDeleteKey() does the
2987 // right thing, but less efficiently and with the cost of more
2989 issueCommandForDeleteKey();
2991 if (m_cmds.count() == 0) {
2992 issueCommandForDeleteKey();
2995 EditCommandPtr lastCommand = m_cmds.last();
2996 if (lastCommand.isInputTextCommand()) {
2997 InputTextCommand &cmd = static_cast<InputTextCommand &>(lastCommand);
2998 cmd.deleteCharacter();
2999 if (cmd.charactersAdded() == 0) {
3000 removeCommand(lastCommand);
3003 else if (lastCommand.isInputNewlineCommand()) {
3004 lastCommand.unapply();
3005 removeCommand(lastCommand);
3008 issueCommandForDeleteKey();
3014 void TypingCommand::removeCommand(const EditCommandPtr &cmd)
3016 // NOTE: If the passed-in command is the last command in the
3017 // composite, we could remove all traces of this typing command
3018 // from the system, including the undo chain. Other editors do
3019 // not do this, but we could.
3022 if (m_cmds.count() == 0)
3023 setEndingSelection(startingSelection());
3025 setEndingSelection(m_cmds.last().endingSelection());
3028 bool TypingCommand::preservesTypingStyle() const
3030 switch (m_commandType) {
3035 case InsertNewlineInQuotedContent:
3038 ASSERT_NOT_REACHED();
3042 bool TypingCommand::isTypingCommand() const
3047 } // namespace khtml