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, ELegacyHTMLStyles usesLegacyStyles)
312 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
314 init(style, Position());
317 StyleChange::StyleChange(CSSStyleDeclarationImpl *style, const Position &position, ELegacyHTMLStyles usesLegacyStyles)
318 : m_applyBold(false), m_applyItalic(false), m_usesLegacyStyles(usesLegacyStyles)
320 init(style, position);
323 void StyleChange::init(CSSStyleDeclarationImpl *style, const Position &position)
327 for (QPtrListIterator<CSSProperty> it(*(style->values())); it.current(); ++it) {
328 CSSProperty *property = it.current();
330 // If position is empty or the position passed in already has the
331 // style, just move on.
332 if (position.isNotNull() && currentlyHasStyle(position, property))
335 // If needed, figure out if this change is a legacy HTML style change.
336 if (m_usesLegacyStyles && checkForLegacyHTMLStyleChange(property))
339 styleText += property->cssText().string();
342 m_cssStyle = styleText.stripWhiteSpace();
345 bool StyleChange::checkForLegacyHTMLStyleChange(const DOM::CSSProperty *property)
347 DOMString valueText(property->value()->cssText());
348 switch (property->id()) {
349 case CSS_PROP_FONT_WEIGHT:
350 if (strcasecmp(valueText, "bold") == 0) {
355 case CSS_PROP_FONT_STYLE:
356 if (strcasecmp(valueText, "italic") == 0 || strcasecmp(valueText, "oblique") == 0) {
357 m_applyItalic = true;
365 bool StyleChange::currentlyHasStyle(const Position &pos, const CSSProperty *property)
367 ASSERT(pos.isNotNull());
368 CSSComputedStyleDeclarationImpl *style = pos.computedStyle();
371 CSSValueImpl *value = style->getPropertyCSSValue(property->id(), DoNotUpdateLayout);
373 return value && strcasecmp(value->cssText(), property->value()->cssText()) == 0;
376 //------------------------------------------------------------------------------------------
379 EditCommand::EditCommand(DocumentImpl *document)
380 : m_document(document), m_state(NotApplied), m_typingStyle(0), m_parent(0)
383 ASSERT(m_document->part());
385 m_startingSelection = m_document->part()->selection();
386 m_endingSelection = m_startingSelection;
388 m_document->part()->setSelection(Selection(), false, true);
391 EditCommand::~EditCommand()
396 m_typingStyle->deref();
399 void EditCommand::apply()
402 ASSERT(m_document->part());
403 ASSERT(state() == NotApplied);
405 KHTMLPart *part = m_document->part();
407 ASSERT(part->selection().isNone());
413 // FIXME: Improve typing style.
414 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
415 if (!preservesTypingStyle())
418 if (!isCompositeStep()) {
419 document()->updateLayout();
420 EditCommandPtr cmd(this);
421 part->appliedEditing(cmd);
425 void EditCommand::unapply()
428 ASSERT(m_document->part());
429 ASSERT(state() == Applied);
431 bool topLevel = !isCompositeStep();
433 KHTMLPart *part = m_document->part();
436 part->setSelection(Selection(), false, true);
438 ASSERT(part->selection().isNone());
442 m_state = NotApplied;
445 document()->updateLayout();
446 EditCommandPtr cmd(this);
447 part->unappliedEditing(cmd);
451 void EditCommand::reapply()
454 ASSERT(m_document->part());
455 ASSERT(state() == NotApplied);
457 bool topLevel = !isCompositeStep();
459 KHTMLPart *part = m_document->part();
462 part->setSelection(Selection(), false, true);
464 ASSERT(part->selection().isNone());
471 document()->updateLayout();
472 EditCommandPtr cmd(this);
473 part->reappliedEditing(cmd);
477 void EditCommand::doReapply()
482 void EditCommand::setStartingSelection(const Selection &s)
484 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
485 cmd->m_startingSelection = s;
488 void EditCommand::setEndingSelection(const Selection &s)
490 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
491 cmd->m_endingSelection = s;
494 void EditCommand::assignTypingStyle(CSSStyleDeclarationImpl *style)
496 CSSStyleDeclarationImpl *old = m_typingStyle;
497 m_typingStyle = style;
499 m_typingStyle->ref();
504 void EditCommand::setTypingStyle(CSSStyleDeclarationImpl *style)
506 // FIXME: Improve typing style.
507 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
508 for (EditCommand *cmd = this; cmd; cmd = cmd->m_parent.get())
509 cmd->assignTypingStyle(style);
512 bool EditCommand::preservesTypingStyle() const
517 bool EditCommand::isInputTextCommand() const
522 bool EditCommand::isTypingCommand() const
527 //------------------------------------------------------------------------------------------
528 // CompositeEditCommand
530 CompositeEditCommand::CompositeEditCommand(DocumentImpl *document)
531 : EditCommand(document)
535 void CompositeEditCommand::doUnapply()
537 if (m_cmds.count() == 0) {
541 for (int i = m_cmds.count() - 1; i >= 0; --i)
542 m_cmds[i]->unapply();
544 setState(NotApplied);
547 void CompositeEditCommand::doReapply()
549 if (m_cmds.count() == 0) {
553 for (QValueList<EditCommandPtr>::ConstIterator it = m_cmds.begin(); it != m_cmds.end(); ++it)
560 // sugary-sweet convenience functions to help create and apply edit commands in composite commands
562 void CompositeEditCommand::applyCommandToComposite(EditCommandPtr &cmd)
564 cmd.setStartingSelection(endingSelection());
565 cmd.setEndingSelection(endingSelection());
571 void CompositeEditCommand::insertNodeBefore(NodeImpl *insertChild, NodeImpl *refChild)
573 EditCommandPtr cmd(new InsertNodeBeforeCommand(document(), insertChild, refChild));
574 applyCommandToComposite(cmd);
577 void CompositeEditCommand::insertNodeAfter(NodeImpl *insertChild, NodeImpl *refChild)
579 if (refChild->parentNode()->lastChild() == refChild) {
580 appendNode(insertChild, refChild->parentNode());
583 ASSERT(refChild->nextSibling());
584 insertNodeBefore(insertChild, refChild->nextSibling());
588 void CompositeEditCommand::insertNodeAt(NodeImpl *insertChild, NodeImpl *refChild, long offset)
590 if (refChild->hasChildNodes() || (refChild->renderer() && refChild->renderer()->isBlockFlow())) {
591 NodeImpl *child = refChild->firstChild();
592 for (long i = 0; child && i < offset; i++)
593 child = child->nextSibling();
595 insertNodeBefore(insertChild, child);
597 appendNode(insertChild, refChild);
599 else if (refChild->caretMinOffset() >= offset) {
600 insertNodeBefore(insertChild, refChild);
602 else if (refChild->isTextNode() && refChild->caretMaxOffset() > offset) {
603 splitTextNode(static_cast<TextImpl *>(refChild), offset);
604 insertNodeBefore(insertChild, refChild);
607 insertNodeAfter(insertChild, refChild);
611 void CompositeEditCommand::appendNode(NodeImpl *appendChild, NodeImpl *parent)
613 EditCommandPtr cmd(new AppendNodeCommand(document(), appendChild, parent));
614 applyCommandToComposite(cmd);
617 void CompositeEditCommand::removeFullySelectedNode(NodeImpl *node)
619 if (isTableStructureNode(node)) {
620 // Do not remove an element of table structure; remove its contents.
621 NodeImpl *child = node->firstChild();
623 NodeImpl *remove = child;
624 child = child->nextSibling();
625 removeFullySelectedNode(remove);
629 EditCommandPtr cmd(new RemoveNodeCommand(document(), node));
630 applyCommandToComposite(cmd);
634 void CompositeEditCommand::removeNode(NodeImpl *removeChild)
636 EditCommandPtr cmd(new RemoveNodeCommand(document(), removeChild));
637 applyCommandToComposite(cmd);
640 void CompositeEditCommand::removeNodePreservingChildren(NodeImpl *removeChild)
642 EditCommandPtr cmd(new RemoveNodePreservingChildrenCommand(document(), removeChild));
643 applyCommandToComposite(cmd);
646 void CompositeEditCommand::splitTextNode(TextImpl *text, long offset)
648 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, offset));
649 applyCommandToComposite(cmd);
652 void CompositeEditCommand::joinTextNodes(TextImpl *text1, TextImpl *text2)
654 EditCommandPtr cmd(new JoinTextNodesCommand(document(), text1, text2));
655 applyCommandToComposite(cmd);
658 void CompositeEditCommand::inputText(const DOMString &text, bool selectInsertedText)
660 InputTextCommand *impl = new InputTextCommand(document());
661 EditCommandPtr cmd(impl);
662 applyCommandToComposite(cmd);
663 impl->input(text, selectInsertedText);
666 void CompositeEditCommand::insertText(TextImpl *node, long offset, const DOMString &text)
668 EditCommandPtr cmd(new InsertTextCommand(document(), node, offset, text));
669 applyCommandToComposite(cmd);
672 void CompositeEditCommand::deleteText(TextImpl *node, long offset, long count)
674 EditCommandPtr cmd(new DeleteTextCommand(document(), node, offset, count));
675 applyCommandToComposite(cmd);
678 void CompositeEditCommand::replaceText(TextImpl *node, long offset, long count, const DOMString &replacementText)
680 EditCommandPtr deleteCommand(new DeleteTextCommand(document(), node, offset, count));
681 applyCommandToComposite(deleteCommand);
682 EditCommandPtr insertCommand(new InsertTextCommand(document(), node, offset, replacementText));
683 applyCommandToComposite(insertCommand);
686 void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete)
688 if (endingSelection().isRange()) {
689 EditCommandPtr cmd(new DeleteSelectionCommand(document(), smartDelete, mergeBlocksAfterDelete));
690 applyCommandToComposite(cmd);
694 void CompositeEditCommand::deleteSelection(const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
696 if (selection.isRange()) {
697 EditCommandPtr cmd(new DeleteSelectionCommand(document(), selection, smartDelete, mergeBlocksAfterDelete));
698 applyCommandToComposite(cmd);
702 void CompositeEditCommand::removeCSSProperty(CSSStyleDeclarationImpl *decl, int property)
704 EditCommandPtr cmd(new RemoveCSSPropertyCommand(document(), decl, property));
705 applyCommandToComposite(cmd);
708 void CompositeEditCommand::removeNodeAttribute(ElementImpl *element, int attribute)
710 EditCommandPtr cmd(new RemoveNodeAttributeCommand(document(), element, attribute));
711 applyCommandToComposite(cmd);
714 void CompositeEditCommand::setNodeAttribute(ElementImpl *element, int attribute, const DOMString &value)
716 EditCommandPtr cmd(new SetNodeAttributeCommand(document(), element, attribute, value));
717 applyCommandToComposite(cmd);
720 NodeImpl *CompositeEditCommand::applyTypingStyle(NodeImpl *child) const
722 // FIXME: This function should share code with ApplyStyleCommand::applyStyleIfNeeded
723 // and ApplyStyleCommand::computeStyleChange.
724 // Both function do similar work, and the common parts could be factored out.
726 // FIXME: Improve typing style.
727 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
729 // update document layout once before running the rest of the function
730 // so that we avoid the expense of updating before each and every call
731 // to check a computed style
732 document()->updateLayout();
734 StyleChange styleChange(document()->part()->typingStyle());
736 NodeImpl *childToAppend = child;
737 int exceptionCode = 0;
739 if (styleChange.applyItalic()) {
740 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
741 ASSERT(exceptionCode == 0);
742 italicElement->appendChild(childToAppend, exceptionCode);
743 ASSERT(exceptionCode == 0);
744 childToAppend = italicElement;
747 if (styleChange.applyBold()) {
748 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
749 ASSERT(exceptionCode == 0);
750 boldElement->appendChild(childToAppend, exceptionCode);
751 ASSERT(exceptionCode == 0);
752 childToAppend = boldElement;
755 if (styleChange.cssStyle().length() > 0) {
756 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
757 ASSERT(exceptionCode == 0);
758 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
759 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
760 styleElement->appendChild(childToAppend, exceptionCode);
761 ASSERT(exceptionCode == 0);
762 childToAppend = styleElement;
765 return childToAppend;
768 void CompositeEditCommand::deleteInsignificantText(TextImpl *textNode, int start, int end)
770 if (!textNode || !textNode->renderer() || start >= end)
773 RenderText *textRenderer = static_cast<RenderText *>(textNode->renderer());
774 InlineTextBox *box = textRenderer->firstTextBox();
776 // whole text node is empty
777 removeNode(textNode);
781 long length = textNode->length();
782 if (start >= length || end > length)
786 InlineTextBox *prevBox = 0;
787 DOMStringImpl *str = 0;
789 // This loop structure works to process all gaps preceding a box,
790 // and also will look at the gap after the last box.
791 while (prevBox || box) {
792 int gapStart = prevBox ? prevBox->m_start + prevBox->m_len : 0;
794 // No more chance for any intersections
797 int gapEnd = box ? box->m_start : length;
798 bool indicesIntersect = start <= gapEnd && end >= gapStart;
799 int gapLen = gapEnd - gapStart;
800 if (indicesIntersect && gapLen > 0) {
801 gapStart = kMax(gapStart, start);
802 gapEnd = kMin(gapEnd, end);
804 str = textNode->string()->substring(start, end - start);
807 // remove text in the gap
808 str->remove(gapStart - start - removed, gapLen);
814 box = box->nextTextBox();
818 // Replace the text between start and end with our pruned version.
820 replaceText(textNode, start, end - start, str);
823 // Assert that we are not going to delete all of the text in the node.
824 // If we were, that should have been done above with the call to
825 // removeNode and return.
826 ASSERT(start > 0 || (unsigned long)end - start < textNode->length());
827 deleteText(textNode, start, end - start);
833 void CompositeEditCommand::deleteInsignificantText(const Position &start, const Position &end)
835 if (start.isNull() || end.isNull())
838 if (RangeImpl::compareBoundaryPoints(start.node(), start.offset(), end.node(), end.offset()) >= 0)
841 NodeImpl *node = start.node();
843 NodeImpl *next = node->traverseNextNode();
845 if (node->isTextNode()) {
846 TextImpl *textNode = static_cast<TextImpl *>(node);
847 bool isStartNode = node == start.node();
848 bool isEndNode = node == end.node();
849 int startOffset = isStartNode ? start.offset() : 0;
850 int endOffset = isEndNode ? end.offset() : textNode->length();
851 deleteInsignificantText(textNode, startOffset, endOffset);
854 if (node == end.node())
860 void CompositeEditCommand::deleteInsignificantTextDownstream(const DOM::Position &pos)
862 Position end = VisiblePosition(pos).next().deepEquivalent().downstream(StayInBlock);
863 deleteInsignificantText(pos, end);
866 void CompositeEditCommand::insertBlockPlaceholderIfNeeded(NodeImpl *node)
868 document()->updateLayout();
870 RenderObject *renderer = node->renderer();
871 if (!renderer->isBlockFlow())
874 if (renderer->height() > 0)
877 int exceptionCode = 0;
878 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
879 ASSERT(exceptionCode == 0);
880 breakNode->setAttribute(ATTR_CLASS, blockPlaceholderClassString());
881 appendNode(breakNode, node);
884 bool CompositeEditCommand::removeBlockPlaceholderIfNeeded(NodeImpl *node)
886 document()->updateLayout();
888 RenderObject *renderer = node->renderer();
889 if (!renderer->isBlockFlow())
892 // This code will remove a block placeholder if it still is at the end
893 // of a block, where we placed it in insertBlockPlaceholderIfNeeded().
894 // Of course, a person who hand-edits an HTML file could move a
895 // placeholder around, but it seems OK to be unconcerned about that case.
896 NodeImpl *last = node->lastChild();
897 if (last && last->isHTMLElement()) {
898 ElementImpl *element = static_cast<ElementImpl *>(last);
899 if (element->getAttribute(ATTR_CLASS) == blockPlaceholderClassString()) {
907 //==========================================================================================
909 //------------------------------------------------------------------------------------------
912 AppendNodeCommand::AppendNodeCommand(DocumentImpl *document, NodeImpl *appendChild, NodeImpl *parentNode)
913 : EditCommand(document), m_appendChild(appendChild), m_parentNode(parentNode)
915 ASSERT(m_appendChild);
916 m_appendChild->ref();
918 ASSERT(m_parentNode);
922 AppendNodeCommand::~AppendNodeCommand()
924 ASSERT(m_appendChild);
925 m_appendChild->deref();
927 ASSERT(m_parentNode);
928 m_parentNode->deref();
931 void AppendNodeCommand::doApply()
933 ASSERT(m_appendChild);
934 ASSERT(m_parentNode);
936 int exceptionCode = 0;
937 m_parentNode->appendChild(m_appendChild, exceptionCode);
938 ASSERT(exceptionCode == 0);
941 void AppendNodeCommand::doUnapply()
943 ASSERT(m_appendChild);
944 ASSERT(m_parentNode);
945 ASSERT(state() == Applied);
947 int exceptionCode = 0;
948 m_parentNode->removeChild(m_appendChild, exceptionCode);
949 ASSERT(exceptionCode == 0);
952 //------------------------------------------------------------------------------------------
955 ApplyStyleCommand::ApplyStyleCommand(DocumentImpl *document, CSSStyleDeclarationImpl *style)
956 : CompositeEditCommand(document), m_style(style)
962 ApplyStyleCommand::~ApplyStyleCommand()
968 void ApplyStyleCommand::doApply()
970 CSSStyleDeclarationImpl *blockStyle = m_style->copyBlockProperties();
972 applyBlockStyle(blockStyle);
974 if (blockStyle->length() < m_style->length()) {
975 CSSStyleDeclarationImpl *inlineStyle = new CSSStyleDeclarationImpl(0, m_style->values());
977 blockStyle->diff(inlineStyle);
978 applyInlineStyle(inlineStyle);
979 inlineStyle->deref();
984 setEndingSelectionNeedsLayout();
987 void ApplyStyleCommand::applyBlockStyle(CSSStyleDeclarationImpl *style)
989 // update document layout once before removing styles
990 // so that we avoid the expense of updating before each and every call
991 // to check a computed style
992 document()->updateLayout();
994 // get positions we want to use for applying style
995 Position start(endingSelection().start());
996 Position end(endingSelection().end());
998 // Remove block styles
999 NodeImpl *beyondEnd = end.node()->traverseNextNode();
1000 NodeImpl *prevBlock = 0;
1001 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1002 NodeImpl *block = node->enclosingBlockFlowElement();
1003 if (block != prevBlock && block->isHTMLElement()) {
1004 removeCSSStyle(style, static_cast<HTMLElementImpl *>(block));
1011 for (NodeImpl *node = start.node(); node != beyondEnd; node = node->traverseNextNode()) {
1012 NodeImpl *block = node->enclosingBlockFlowElement();
1013 if (block != prevBlock && block->isHTMLElement()) {
1014 addBlockStyleIfNeeded(style, static_cast<HTMLElementImpl *>(block));
1020 void ApplyStyleCommand::applyInlineStyle(CSSStyleDeclarationImpl *style)
1022 // adjust to the positions we want to use for applying style
1023 Position start(endingSelection().start().downstream(StayInBlock).equivalentRangeCompliantPosition());
1024 Position end(endingSelection().end().upstream(StayInBlock));
1026 // update document layout once before removing styles
1027 // so that we avoid the expense of updating before each and every call
1028 // to check a computed style
1029 document()->updateLayout();
1031 // Remove style from the selection.
1032 // Use the upstream position of the start for removing style.
1033 // This will ensure we remove all traces of the relevant styles from the selection
1034 // and prevent us from adding redundant ones, as described in:
1035 // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
1036 removeInlineStyle(style, start.upstream(), end);
1038 bool splitStart = splitTextAtStartIfNeeded(start, end);
1040 start = endingSelection().start();
1041 end = endingSelection().end();
1043 splitTextAtEndIfNeeded(start, end);
1044 start = endingSelection().start();
1045 end = endingSelection().end();
1047 // update document layout once before running the rest of the function
1048 // so that we avoid the expense of updating before each and every call
1049 // to check a computed style
1050 document()->updateLayout();
1052 if (start.node() == end.node()) {
1053 // simple case...start and end are the same node
1054 addInlineStyleIfNeeded(style, start.node(), end.node());
1057 NodeImpl *node = start.node();
1059 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1060 NodeImpl *runStart = node;
1062 NodeImpl *next = node->traverseNextNode();
1063 // Break if node is the end node, or if the next node does not fit in with
1064 // the current group.
1065 if (node == end.node() ||
1066 runStart->parentNode() != next->parentNode() ||
1067 (next->isHTMLElement() && next->id() != ID_BR) ||
1068 (next->renderer() && !next->renderer()->isInline()))
1072 // Now apply style to the run we found.
1073 addInlineStyleIfNeeded(style, runStart, node);
1075 if (node == end.node())
1077 node = node->traverseNextNode();
1082 //------------------------------------------------------------------------------------------
1083 // ApplyStyleCommand: style-removal helpers
1085 bool ApplyStyleCommand::isHTMLStyleNode(CSSStyleDeclarationImpl *style, HTMLElementImpl *elem)
1087 for (QPtrListIterator<CSSProperty> it(*(style->values())); it.current(); ++it) {
1088 CSSProperty *property = it.current();
1089 switch (property->id()) {
1090 case CSS_PROP_FONT_WEIGHT:
1091 if (elem->id() == ID_B)
1094 case CSS_PROP_FONT_STYLE:
1095 if (elem->id() == ID_I)
1104 void ApplyStyleCommand::removeHTMLStyleNode(HTMLElementImpl *elem)
1106 // This node can be removed.
1107 // EDIT FIXME: This does not handle the case where the node
1108 // has attributes. But how often do people add attributes to <B> tags?
1109 // Not so often I think.
1111 removeNodePreservingChildren(elem);
1114 void ApplyStyleCommand::removeCSSStyle(CSSStyleDeclarationImpl *style, HTMLElementImpl *elem)
1119 CSSStyleDeclarationImpl *decl = elem->inlineStyleDecl();
1123 for (QPtrListIterator<CSSProperty> it(*(style->values())); it.current(); ++it) {
1124 CSSProperty *property = it.current();
1125 if (decl->getPropertyCSSValue(property->id()))
1126 removeCSSProperty(decl, property->id());
1129 if (elem->id() == ID_SPAN && elem->renderer() && elem->renderer()->isInline()) {
1130 // Check to see if the span is one we added to apply style.
1131 // If it is, and there are no more attributes on the span other than our
1132 // class marker, remove the span.
1133 if (decl->values()->count() == 0) {
1134 removeNodeAttribute(elem, ATTR_STYLE);
1135 NamedAttrMapImpl *map = elem->attributes();
1136 if (map && map->length() == 1 && elem->getAttribute(ATTR_CLASS) == styleSpanClassString())
1137 removeNodePreservingChildren(elem);
1142 void ApplyStyleCommand::removeBlockStyle(CSSStyleDeclarationImpl *style, const Position &start, const Position &end)
1144 ASSERT(start.isNotNull());
1145 ASSERT(end.isNotNull());
1146 ASSERT(start.node()->inDocument());
1147 ASSERT(end.node()->inDocument());
1148 ASSERT(RangeImpl::compareBoundaryPoints(start.node(), start.offset(), end.node(), end.offset()) <= 0);
1152 void ApplyStyleCommand::removeInlineStyle(CSSStyleDeclarationImpl *style, const Position &start, const Position &end)
1154 ASSERT(start.isNotNull());
1155 ASSERT(end.isNotNull());
1156 ASSERT(start.node()->inDocument());
1157 ASSERT(end.node()->inDocument());
1158 ASSERT(RangeImpl::compareBoundaryPoints(start.node(), start.offset(), end.node(), end.offset()) <= 0);
1160 NodeImpl *node = start.node();
1162 NodeImpl *next = node->traverseNextNode();
1163 if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
1164 HTMLElementImpl *elem = static_cast<HTMLElementImpl *>(node);
1165 if (isHTMLStyleNode(style, elem))
1166 removeHTMLStyleNode(elem);
1168 removeCSSStyle(style, elem);
1170 if (node == end.node())
1176 bool ApplyStyleCommand::nodeFullySelected(NodeImpl *node, const Position &start, const Position &end) const
1180 Position pos = Position(node, node->childNodeCount()).upstream();
1181 return RangeImpl::compareBoundaryPoints(node, 0, start.node(), start.offset()) >= 0 &&
1182 RangeImpl::compareBoundaryPoints(pos.node(), pos.offset(), end.node(), end.offset()) <= 0;
1185 //------------------------------------------------------------------------------------------
1186 // ApplyStyleCommand: style-application helpers
1189 bool ApplyStyleCommand::splitTextAtStartIfNeeded(const Position &start, const Position &end)
1191 if (start.node()->isTextNode() && start.offset() > start.node()->caretMinOffset() && start.offset() < start.node()->caretMaxOffset()) {
1192 long endOffsetAdjustment = start.node() == end.node() ? start.offset() : 0;
1193 TextImpl *text = static_cast<TextImpl *>(start.node());
1194 EditCommandPtr cmd(new SplitTextNodeCommand(document(), text, start.offset()));
1195 applyCommandToComposite(cmd);
1196 setEndingSelection(Selection(Position(start.node(), 0), Position(end.node(), end.offset() - endOffsetAdjustment)));
1202 NodeImpl *ApplyStyleCommand::splitTextAtEndIfNeeded(const Position &start, const Position &end)
1204 if (end.node()->isTextNode() && end.offset() > end.node()->caretMinOffset() && end.offset() < end.node()->caretMaxOffset()) {
1205 TextImpl *text = static_cast<TextImpl *>(end.node());
1206 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, end.offset());
1207 EditCommandPtr cmd(impl);
1208 applyCommandToComposite(cmd);
1209 NodeImpl *startNode = start.node() == end.node() ? impl->node()->previousSibling() : start.node();
1211 setEndingSelection(Selection(Position(startNode, start.offset()), Position(impl->node()->previousSibling(), impl->node()->previousSibling()->caretMaxOffset())));
1212 return impl->node()->previousSibling();
1217 void ApplyStyleCommand::surroundNodeRangeWithElement(NodeImpl *startNode, NodeImpl *endNode, ElementImpl *element)
1223 NodeImpl *node = startNode;
1225 NodeImpl *next = node->traverseNextNode();
1226 if (node->childNodeCount() == 0 && node->renderer() && node->renderer()->isInline()) {
1228 appendNode(node, element);
1230 if (node == endNode)
1236 void ApplyStyleCommand::addBlockStyleIfNeeded(CSSStyleDeclarationImpl *style, HTMLElementImpl *block)
1238 // Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
1240 StyleChange styleChange(style, Position(block, 0), StyleChange::DoNotUseLegacyHTMLStyles);
1241 if (styleChange.cssStyle().length() > 0) {
1242 DOMString cssText = styleChange.cssStyle();
1243 CSSStyleDeclarationImpl *decl = block->inlineStyleDecl();
1245 cssText += decl->cssText();
1246 block->setAttribute(ATTR_STYLE, cssText);
1250 void ApplyStyleCommand::addInlineStyleIfNeeded(CSSStyleDeclarationImpl *style, NodeImpl *startNode, NodeImpl *endNode)
1252 // FIXME: This function should share code with CompositeEditCommand::applyTypingStyle.
1253 // Both functions do similar work, and the common parts could be factored out.
1255 StyleChange styleChange(style, Position(startNode, 0));
1256 int exceptionCode = 0;
1258 if (styleChange.cssStyle().length() > 0) {
1259 ElementImpl *styleElement = document()->createHTMLElement("SPAN", exceptionCode);
1260 ASSERT(exceptionCode == 0);
1261 styleElement->setAttribute(ATTR_STYLE, styleChange.cssStyle());
1262 styleElement->setAttribute(ATTR_CLASS, styleSpanClassString());
1263 insertNodeBefore(styleElement, startNode);
1264 surroundNodeRangeWithElement(startNode, endNode, styleElement);
1267 if (styleChange.applyBold()) {
1268 ElementImpl *boldElement = document()->createHTMLElement("B", exceptionCode);
1269 ASSERT(exceptionCode == 0);
1270 insertNodeBefore(boldElement, startNode);
1271 surroundNodeRangeWithElement(startNode, endNode, boldElement);
1274 if (styleChange.applyItalic()) {
1275 ElementImpl *italicElement = document()->createHTMLElement("I", exceptionCode);
1276 ASSERT(exceptionCode == 0);
1277 insertNodeBefore(italicElement, startNode);
1278 surroundNodeRangeWithElement(startNode, endNode, italicElement);
1282 Position ApplyStyleCommand::positionInsertionPoint(Position pos)
1284 if (pos.node()->isTextNode() && (pos.offset() > 0 && pos.offset() < pos.node()->maxOffset())) {
1285 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), static_cast<TextImpl *>(pos.node()), pos.offset());
1286 EditCommandPtr split(impl);
1288 pos = Position(impl->node(), 0);
1292 // EDIT FIXME: If modified to work with the internals of applying style,
1293 // this code can work to optimize cases where a style change is taking place on
1294 // a boundary between nodes where one of the nodes has the desired style. In other
1295 // words, it is possible for content to be merged into existing nodes rather than adding
1296 // additional markup.
1297 if (currentlyHasStyle(pos))
1301 if (pos.offset() >= pos.node()->caretMaxOffset()) {
1302 NodeImpl *nextNode = pos.node()->traverseNextNode();
1304 Position next = Position(nextNode, 0);
1305 if (currentlyHasStyle(next))
1310 // try previous node
1311 if (pos.offset() <= pos.node()->caretMinOffset()) {
1312 NodeImpl *prevNode = pos.node()->traversePreviousNode();
1314 Position prev = Position(prevNode, prevNode->maxOffset());
1315 if (currentlyHasStyle(prev))
1324 //------------------------------------------------------------------------------------------
1325 // DeleteSelectionCommand
1327 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
1328 : CompositeEditCommand(document),
1329 m_hasSelectionToDelete(false),
1330 m_smartDelete(smartDelete),
1331 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1339 DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const Selection &selection, bool smartDelete, bool mergeBlocksAfterDelete)
1340 : CompositeEditCommand(document),
1341 m_hasSelectionToDelete(true),
1342 m_smartDelete(smartDelete),
1343 m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
1344 m_selectionToDelete(selection),
1352 void DeleteSelectionCommand::initializePositionData()
1354 Position start = startPositionForDelete();
1355 Position end = endPositionForDelete();
1357 m_upstreamStart = Position(start.upstream(StayInBlock));
1358 m_downstreamStart = Position(start.downstream(StayInBlock));
1359 m_upstreamEnd = Position(end.upstream(StayInBlock));
1360 m_downstreamEnd = Position(end.downstream(StayInBlock));
1362 m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition();
1363 m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition();
1364 m_trailingWhitespaceValid = true;
1366 debugPosition("m_upstreamStart ", m_upstreamStart);
1367 debugPosition("m_downstreamStart ", m_downstreamStart);
1368 debugPosition("m_upstreamEnd ", m_upstreamEnd);
1369 debugPosition("m_downstreamEnd ", m_downstreamEnd);
1370 debugPosition("m_leadingWhitespace ", m_leadingWhitespace);
1371 debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
1373 m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
1374 m_startBlock->ref();
1375 m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
1378 m_startNode = m_upstreamStart.node();
1382 Position DeleteSelectionCommand::startPositionForDelete() const
1384 Position pos = m_selectionToDelete.start();
1385 ASSERT(pos.node()->inDocument());
1387 ElementImpl *rootElement = pos.node()->rootEditableElement();
1388 Position rootStart = Position(rootElement, 0);
1389 if (pos == VisiblePosition(rootStart).deepEquivalent())
1391 else if (m_smartDelete && pos.leadingWhitespacePosition().isNotNull())
1392 pos = VisiblePosition(pos).previous().deepEquivalent();
1396 Position DeleteSelectionCommand::endPositionForDelete() const
1398 Position pos = m_selectionToDelete.end();
1399 ASSERT(pos.node()->inDocument());
1401 ElementImpl *rootElement = pos.node()->rootEditableElement();
1402 Position rootEnd = Position(rootElement, rootElement ? rootElement->childNodeCount() : 0).equivalentDeepPosition();
1403 if (pos == VisiblePosition(rootEnd).deepEquivalent())
1405 else if (m_smartDelete && pos.leadingWhitespacePosition().isNotNull())
1406 pos = VisiblePosition(pos).next().deepEquivalent();
1410 void DeleteSelectionCommand::saveTypingStyleState()
1412 // Figure out the typing style in effect before the delete is done.
1413 // FIXME: Improve typing style.
1414 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1415 CSSComputedStyleDeclarationImpl *computedStyle = m_downstreamStart.computedStyle();
1416 computedStyle->ref();
1417 m_typingStyle = computedStyle->copyInheritableProperties();
1418 m_typingStyle->ref();
1419 computedStyle->deref();
1422 bool DeleteSelectionCommand::canPerformSpecialCaseBRDelete()
1424 // Check for special-case where the selection contains only a BR on a line by itself after another BR.
1425 bool upstreamStartIsBR = m_startNode->id() == ID_BR;
1426 bool downstreamStartIsBR = m_downstreamStart.node()->id() == ID_BR;
1427 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
1428 if (isBROnLineByItself) {
1429 removeNode(m_downstreamStart.node());
1430 m_endingPosition = m_upstreamStart;
1431 m_mergeBlocksAfterDelete = false;
1435 // Check for special-case where the selection contains only a BR right after a block ended.
1436 bool downstreamEndIsBR = m_downstreamEnd.node()->id() == ID_BR;
1437 Position upstreamUpstreamStart = m_upstreamStart.upstream();
1438 bool startIsBRAfterBlock = downstreamEndIsBR && m_downstreamEnd.node()->enclosingBlockFlowElement() != upstreamUpstreamStart.node()->enclosingBlockFlowElement();
1439 if (startIsBRAfterBlock) {
1440 removeNode(m_downstreamEnd.node());
1441 m_endingPosition = upstreamUpstreamStart;
1442 m_mergeBlocksAfterDelete = false;
1446 // Not a special-case delete per se, but we can detect that the merging of content between blocks
1447 // should not be done.
1448 if (upstreamStartIsBR && downstreamStartIsBR)
1449 m_mergeBlocksAfterDelete = false;
1454 void DeleteSelectionCommand::performGeneralDelete()
1456 int startOffset = m_upstreamStart.offset();
1457 if (startOffset >= m_startNode->caretMaxOffset()) {
1458 if (m_startNode->isTextNode()) {
1459 // Delete any insignificant text from this node.
1460 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1461 if (text->length() > (unsigned)m_startNode->caretMaxOffset())
1462 deleteText(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
1464 // shift the start node to the next
1465 NodeImpl *old = m_startNode;
1466 m_startNode = old->traverseNextNode();
1472 if (m_startNode == m_downstreamEnd.node()) {
1473 // handle delete in one node
1474 if (!m_startNode->renderer() ||
1475 (startOffset <= m_startNode->caretMinOffset() && m_downstreamEnd.offset() >= m_startNode->caretMaxOffset())) {
1477 removeFullySelectedNode(m_startNode);
1479 else if (m_downstreamEnd.offset() - startOffset > 0) {
1480 // in a text node that needs to be trimmed
1481 TextImpl *text = static_cast<TextImpl *>(m_startNode);
1482 deleteText(text, startOffset, m_downstreamEnd.offset() - startOffset);
1483 m_trailingWhitespaceValid = false;
1487 NodeImpl *node = m_startNode;
1489 if (startOffset > 0) {
1490 // in a text node that needs to be trimmed
1491 TextImpl *text = static_cast<TextImpl *>(node);
1492 deleteText(text, startOffset, text->length() - startOffset);
1493 node = node->traverseNextNode();
1496 // handle deleting all nodes that are completely selected
1497 while (node && node != m_downstreamEnd.node()) {
1498 if (!m_downstreamEnd.node()->isAncestor(node)) {
1499 NodeImpl *nextNode = node->traverseNextSibling();
1500 removeFullySelectedNode(node);
1504 NodeImpl *n = node->lastChild();
1505 while (n && n->lastChild())
1507 if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1508 NodeImpl *nextNode = node->traverseNextSibling();
1509 removeFullySelectedNode(node);
1513 node = node->traverseNextNode();
1518 if (m_downstreamEnd.node() != m_startNode && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
1519 if (m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
1520 // need to delete whole node
1521 // we can get here if this is the last node in the block
1522 removeFullySelectedNode(m_downstreamEnd.node());
1523 m_trailingWhitespaceValid = false;
1526 // in a text node that needs to be trimmed
1527 TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
1528 if (m_downstreamEnd.offset() > 0) {
1529 deleteText(text, 0, m_downstreamEnd.offset());
1530 m_trailingWhitespaceValid = false;
1533 if (!m_downstreamEnd.node()->inDocument() && m_downstreamEnd.node()->inDocument())
1534 m_endingPosition = Position(m_downstreamEnd.node(), 0);
1539 void DeleteSelectionCommand::fixupWhitespace()
1541 document()->updateLayout();
1542 if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
1543 LOG(Editing, "replace leading");
1544 TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
1545 replaceText(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
1547 else if (m_trailingWhitespace.isNotNull()) {
1548 if (m_trailingWhitespaceValid) {
1549 if (!m_trailingWhitespace.isRenderedCharacter()) {
1550 LOG(Editing, "replace trailing [valid]");
1551 TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
1552 replaceText(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
1556 Position pos = m_endingPosition.downstream(StayInBlock);
1557 pos = Position(pos.node(), pos.offset() - 1);
1558 if (isWS(pos) && !pos.isRenderedCharacter()) {
1559 LOG(Editing, "replace trailing [invalid]");
1560 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1561 replaceText(textNode, pos.offset(), 1, nonBreakingSpaceString());
1562 // need to adjust ending position since the trailing position is not valid.
1563 m_endingPosition = pos;
1569 // This function moves nodes in the block containing startNode to dstBlock, starting
1570 // from startNode and proceeding to the end of the block. Nodes in the block containing
1571 // startNode that appear in document order before startNode are not moved.
1572 // This function is an important helper for deleting selections that cross block
1574 void DeleteSelectionCommand::moveNodesAfterNode()
1576 if (!m_mergeBlocksAfterDelete)
1579 if (m_endBlock == m_startBlock)
1582 NodeImpl *startNode = m_downstreamEnd.node();
1583 NodeImpl *dstNode = m_upstreamStart.node();
1585 if (!startNode->inDocument() || !dstNode->inDocument())
1588 NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
1589 if (isTableStructureNode(startBlock))
1590 // Do not move content between parts of a table
1593 // Now that we are about to add content, check to see if a placeholder element
1595 removeBlockPlaceholderIfNeeded(startBlock);
1597 NodeImpl *node = startNode == startBlock ? startBlock->firstChild() : startNode;
1600 NodeImpl *refNode = dstNode;
1601 while (node && node->isAncestor(startBlock)) {
1602 NodeImpl *moveNode = node;
1603 node = node->nextSibling();
1604 removeNode(moveNode);
1605 insertNodeAfter(moveNode, refNode);
1609 // If the startBlock no longer has any kids, we may need to deal with adding a BR
1610 // to make the layout come out right. Consider this document:
1616 // Placing the insertion before before the 'T' of 'Two' and hitting delete will
1617 // move the contents of the div to the block containing 'One' and delete the div.
1618 // This will have the side effect of moving 'Three' on to the same line as 'One'
1619 // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
1620 // This may not be ideal, but it is better than nothing.
1621 document()->updateLayout();
1622 if (startBlock->renderer() && startBlock->renderer()->height() == 0) {
1623 removeNode(startBlock);
1624 if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
1625 int exceptionCode = 0;
1626 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1627 ASSERT(exceptionCode == 0);
1628 insertNodeAfter(breakNode, refNode);
1633 void DeleteSelectionCommand::calculateEndingPosition()
1635 if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
1638 m_endingPosition = m_upstreamStart;
1639 if (m_endingPosition.node()->inDocument())
1642 m_endingPosition = m_downstreamEnd;
1643 if (m_endingPosition.node()->inDocument())
1646 m_endingPosition = Position(m_startBlock, 0);
1647 if (m_endingPosition.node()->inDocument())
1650 m_endingPosition = Position(m_endBlock, 0);
1651 if (m_endingPosition.node()->inDocument())
1654 m_endingPosition = Position(document()->documentElement(), 0);
1657 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
1659 // Compute the difference between the style before the delete and the style now
1660 // after the delete has been done. Set this style on the part, so other editing
1661 // commands being composed with this one will work, and also cache it on the command,
1662 // so the KHTMLPart::appliedEditing can set it after the whole composite command
1664 // FIXME: Improve typing style.
1665 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1666 if (m_startNode == m_endingPosition.node())
1667 document()->part()->setTypingStyle(0);
1669 CSSComputedStyleDeclarationImpl endingStyle(m_endingPosition.node());
1670 endingStyle.diff(m_typingStyle);
1671 if (!m_typingStyle->length()) {
1672 m_typingStyle->deref();
1675 document()->part()->setTypingStyle(m_typingStyle);
1676 setTypingStyle(m_typingStyle);
1680 void DeleteSelectionCommand::clearTransientState()
1682 m_selectionToDelete.clear();
1683 m_upstreamStart.clear();
1684 m_downstreamStart.clear();
1685 m_upstreamEnd.clear();
1686 m_downstreamEnd.clear();
1687 m_endingPosition.clear();
1688 m_leadingWhitespace.clear();
1689 m_trailingWhitespace.clear();
1692 m_startBlock->deref();
1696 m_endBlock->deref();
1700 m_startNode->deref();
1703 if (m_typingStyle) {
1704 m_typingStyle->deref();
1709 void DeleteSelectionCommand::doApply()
1711 // If selection has not been set to a custom selection when the command was created,
1712 // use the current ending selection.
1713 if (!m_hasSelectionToDelete)
1714 m_selectionToDelete = endingSelection();
1716 if (!m_selectionToDelete.isRange())
1719 initializePositionData();
1721 if (!m_startBlock || !m_endBlock) {
1722 // Can't figure out what blocks we're in. This can happen if
1723 // the document structure is not what we are expecting, like if
1724 // the document has no body element, or if the editable block
1725 // has been changed to display: inline. Some day it might
1726 // be nice to be able to deal with this, but for now, bail.
1727 clearTransientState();
1731 // Delete any text that may hinder our ability to fixup whitespace after the detele
1732 deleteInsignificantTextDownstream(m_trailingWhitespace);
1734 saveTypingStyleState();
1736 if (!canPerformSpecialCaseBRDelete())
1737 performGeneralDelete();
1739 // Do block merge if start and end of selection are in different blocks.
1740 moveNodesAfterNode();
1742 calculateEndingPosition();
1745 // If the delete emptied a block, add in a placeholder so the block does not
1746 // seem to disappear.
1747 insertBlockPlaceholderIfNeeded(m_endingPosition.node());
1748 calculateTypingStyleAfterDelete();
1749 setEndingSelection(m_endingPosition);
1750 debugPosition("endingPosition ", m_endingPosition);
1751 clearTransientState();
1754 bool DeleteSelectionCommand::preservesTypingStyle() const
1759 //------------------------------------------------------------------------------------------
1760 // DeleteTextCommand
1762 DeleteTextCommand::DeleteTextCommand(DocumentImpl *document, TextImpl *node, long offset, long count)
1763 : EditCommand(document), m_node(node), m_offset(offset), m_count(count)
1766 ASSERT(m_offset >= 0);
1767 ASSERT(m_offset < (long)m_node->length());
1768 ASSERT(m_count >= 0);
1773 DeleteTextCommand::~DeleteTextCommand()
1779 void DeleteTextCommand::doApply()
1783 int exceptionCode = 0;
1784 m_text = m_node->substringData(m_offset, m_count, exceptionCode);
1785 ASSERT(exceptionCode == 0);
1787 m_node->deleteData(m_offset, m_count, exceptionCode);
1788 ASSERT(exceptionCode == 0);
1791 void DeleteTextCommand::doUnapply()
1794 ASSERT(!m_text.isEmpty());
1796 int exceptionCode = 0;
1797 m_node->insertData(m_offset, m_text, exceptionCode);
1798 ASSERT(exceptionCode == 0);
1801 //------------------------------------------------------------------------------------------
1802 // InputNewlineCommand
1804 InputNewlineCommand::InputNewlineCommand(DocumentImpl *document)
1805 : CompositeEditCommand(document)
1809 void InputNewlineCommand::insertNodeAfterPosition(NodeImpl *node, const Position &pos)
1811 // Insert the BR after the caret position. In the case the
1812 // position is a block, do an append. We don't want to insert
1813 // the BR *after* the block.
1814 Position upstream(pos.upstream(StayInBlock));
1815 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1816 if (cb == pos.node())
1817 appendNode(node, cb);
1819 insertNodeAfter(node, pos.node());
1822 void InputNewlineCommand::insertNodeBeforePosition(NodeImpl *node, const Position &pos)
1824 // Insert the BR after the caret position. In the case the
1825 // position is a block, do an append. We don't want to insert
1826 // the BR *before* the block.
1827 Position upstream(pos.upstream(StayInBlock));
1828 NodeImpl *cb = pos.node()->enclosingBlockFlowElement();
1829 if (cb == pos.node())
1830 appendNode(node, cb);
1832 insertNodeBefore(node, pos.node());
1835 void InputNewlineCommand::doApply()
1838 Selection selection = endingSelection();
1840 int exceptionCode = 0;
1841 ElementImpl *breakNode = document()->createHTMLElement("BR", exceptionCode);
1842 ASSERT(exceptionCode == 0);
1844 NodeImpl *nodeToInsert = breakNode;
1846 // Handle the case where there is a typing style.
1847 // FIXME: Improve typing style.
1848 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
1849 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
1850 if (typingStyle && typingStyle->length() > 0)
1851 nodeToInsert = applyTypingStyle(breakNode);
1853 Position pos(selection.start().upstream(StayInBlock));
1854 bool atStart = pos.offset() <= pos.node()->caretMinOffset();
1855 bool atEnd = pos.offset() >= pos.node()->caretMaxOffset();
1856 bool atEndOfBlock = VisiblePosition(pos).isLastInBlock();
1859 LOG(Editing, "input newline case 1");
1860 // Check for a trailing BR. If there isn't one, we'll need to insert an "extra" one.
1861 // This makes the "real" BR we want to insert appear in the rendering without any
1862 // significant side effects (and no real worries either since you can't arrow past
1864 if (pos.node()->id() == ID_BR && pos.offset() == 0) {
1865 // Already placed in a trailing BR. Insert "real" BR before it and leave the selection alone.
1866 insertNodeBefore(nodeToInsert, pos.node());
1869 NodeImpl *next = pos.node()->traverseNextNode();
1870 bool hasTrailingBR = next && next->id() == ID_BR && pos.node()->enclosingBlockFlowElement() == next->enclosingBlockFlowElement();
1871 insertNodeAfterPosition(nodeToInsert, pos);
1872 if (hasTrailingBR) {
1873 setEndingSelection(Position(next, 0));
1876 // Insert an "extra" BR at the end of the block.
1877 ElementImpl *extraBreakNode = document()->createHTMLElement("BR", exceptionCode);
1878 ASSERT(exceptionCode == 0);
1879 insertNodeAfter(extraBreakNode, nodeToInsert);
1880 setEndingSelection(Position(extraBreakNode, 0));
1885 LOG(Editing, "input newline case 2");
1886 // Insert node before downstream position, and place caret there as well.
1887 Position endingPosition = pos.downstream(StayInBlock);
1888 insertNodeBeforePosition(nodeToInsert, endingPosition);
1889 setEndingSelection(endingPosition);
1892 LOG(Editing, "input newline case 3");
1893 // Insert BR after this node. Place caret in the position that is downstream
1894 // of the current position, reckoned before inserting the BR in between.
1895 Position endingPosition = pos.downstream(StayInBlock);
1896 insertNodeAfterPosition(nodeToInsert, pos);
1897 setEndingSelection(endingPosition);
1900 // Split a text node
1901 LOG(Editing, "input newline case 4");
1902 ASSERT(pos.node()->isTextNode());
1905 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
1906 TextImpl *textBeforeNode = document()->createTextNode(textNode->substringData(0, selection.start().offset(), exceptionCode));
1907 deleteText(textNode, 0, pos.offset());
1908 insertNodeBefore(textBeforeNode, textNode);
1909 insertNodeBefore(nodeToInsert, textNode);
1910 Position endingPosition = Position(textNode, 0);
1912 // Handle whitespace that occurs after the split
1913 document()->updateLayout();
1914 if (!endingPosition.isRenderedCharacter()) {
1915 // Clear out all whitespace and insert one non-breaking space
1916 deleteInsignificantTextDownstream(endingPosition);
1917 insertText(textNode, 0, nonBreakingSpaceString());
1920 setEndingSelection(endingPosition);
1924 //------------------------------------------------------------------------------------------
1925 // InputNewlineInQuotedContentCommand
1927 InputNewlineInQuotedContentCommand::InputNewlineInQuotedContentCommand(DocumentImpl *document)
1928 : CompositeEditCommand(document)
1930 ancestors.setAutoDelete(true);
1931 clonedNodes.setAutoDelete(true);
1934 InputNewlineInQuotedContentCommand::~InputNewlineInQuotedContentCommand()
1937 m_breakNode->deref();
1940 bool InputNewlineInQuotedContentCommand::isMailBlockquote(const NodeImpl *node) const
1942 if (!node || !node->renderer() || !node->isElementNode() && node->id() != ID_BLOCKQUOTE)
1945 return static_cast<const ElementImpl *>(node)->getAttribute("type") == "cite";
1948 bool InputNewlineInQuotedContentCommand::isLastVisiblePositionInBlockquote(const VisiblePosition &pos, const NodeImpl *blockquote) const
1953 VisiblePosition next = pos.next();
1954 return next.isNull() || !next.deepEquivalent().node()->isAncestor(blockquote);
1957 void InputNewlineInQuotedContentCommand::doApply()
1959 Selection selection = endingSelection();
1960 if (selection.isNone())
1963 // Delete the current selection.
1964 Position pos = selection.start();
1965 if (selection.isRange()) {
1966 deleteSelection(false, false);
1967 pos = endingSelection().start().upstream();
1970 // Find the top-most blockquote from the start.
1971 NodeImpl *startNode = pos.node();
1972 NodeImpl *topBlockquote = 0;
1973 for (NodeImpl *n = startNode->parentNode(); n; n = n->parentNode()) {
1974 if (isMailBlockquote(n))
1977 if (!topBlockquote || !topBlockquote->parentNode())
1980 // Build up list of ancestors in between the start node and the top blockquote.
1981 for (NodeImpl *n = startNode->parentNode(); n && n != topBlockquote; n = n->parentNode())
1982 ancestors.prepend(n);
1984 // Insert a break after the top blockquote.
1985 int exceptionCode = 0;
1986 m_breakNode = document()->createHTMLElement("BR", exceptionCode);
1988 ASSERT(exceptionCode == 0);
1989 insertNodeAfter(m_breakNode, topBlockquote);
1991 if (!isLastVisiblePositionInBlockquote(VisiblePosition(pos), topBlockquote)) {
1992 // Split at pos if in the middle of a text node.
1993 if (startNode->isTextNode()) {
1994 TextImpl *textNode = static_cast<TextImpl *>(startNode);
1995 bool atEnd = (unsigned long)pos.offset() >= textNode->length();
1996 if (pos.offset() > 0 && !atEnd) {
1997 SplitTextNodeCommand *splitCommand = new SplitTextNodeCommand(document(), textNode, pos.offset());
1998 EditCommandPtr cmd(splitCommand);
1999 applyCommandToComposite(cmd);
2000 startNode = splitCommand->node();
2001 pos = Position(startNode, 0);
2004 startNode = startNode->traverseNextNode();
2008 else if (pos.offset() > 0) {
2009 startNode = startNode->traverseNextNode();
2013 // Insert a clone of the top blockquote after the break.
2014 NodeImpl *clonedBlockquote = topBlockquote->cloneNode(false);
2015 clonedNodes.append(clonedBlockquote);
2016 insertNodeAfter(clonedBlockquote, m_breakNode);
2018 // Make clones of ancestors in between the start node and the top blockquote.
2019 NodeImpl *parent = clonedBlockquote;
2020 for (QPtrListIterator<NodeImpl> it(ancestors); it.current(); ++it) {
2021 NodeImpl *child = it.current()->cloneNode(false); // shallow clone
2022 clonedNodes.append(child);
2023 appendNode(child, parent);
2027 // Move the start node and the siblings of the start node.
2028 NodeImpl *n = startNode;
2029 bool startIsBR = n->id() == ID_BR;
2031 n = n->nextSibling();
2033 NodeImpl *next = n->nextSibling();
2035 appendNode(n, parent);
2039 // Move everything after the start node.
2040 NodeImpl *leftParent = ancestors.last();
2044 leftParent = topBlockquote;
2045 ElementImpl *b = document()->createHTMLElement("BR", exceptionCode);
2046 clonedNodes.append(b);
2047 ASSERT(exceptionCode == 0);
2048 appendNode(b, leftParent);
2051 leftParent = ancestors.last();
2052 while (leftParent && leftParent != topBlockquote) {
2053 parent = parent->parentNode();
2054 NodeImpl *n = leftParent->nextSibling();
2056 NodeImpl *next = n->nextSibling();
2058 appendNode(n, parent);
2061 leftParent = leftParent->parentNode();
2065 // Put the selection right before the break.
2066 setEndingSelection(Position(m_breakNode, 0));
2069 //------------------------------------------------------------------------------------------
2072 InputTextCommand::InputTextCommand(DocumentImpl *document)
2073 : CompositeEditCommand(document), m_charactersAdded(0)
2077 void InputTextCommand::doApply()
2081 void InputTextCommand::deleteCharacter()
2083 ASSERT(state() == Applied);
2085 Selection selection = endingSelection();
2087 if (!selection.start().node()->isTextNode())
2090 int exceptionCode = 0;
2091 int offset = selection.start().offset() - 1;
2092 if (offset >= selection.start().node()->caretMinOffset()) {
2093 TextImpl *textNode = static_cast<TextImpl *>(selection.start().node());
2094 textNode->deleteData(offset, 1, exceptionCode);
2095 ASSERT(exceptionCode == 0);
2096 selection = Selection(Position(textNode, offset));
2097 setEndingSelection(selection);
2098 m_charactersAdded--;
2102 Position InputTextCommand::prepareForTextInsertion(bool adjustDownstream)
2104 // Prepare for text input by looking at the current position.
2105 // It may be necessary to insert a text node to receive characters.
2106 Selection selection = endingSelection();
2107 ASSERT(selection.isCaret());
2109 Position pos = selection.start();
2110 if (adjustDownstream)
2111 pos = pos.downstream(StayInBlock);
2113 pos = pos.upstream(StayInBlock);
2115 if (!pos.node()->isTextNode()) {
2116 NodeImpl *textNode = document()->createEditingTextNode("");
2117 NodeImpl *nodeToInsert = textNode;
2119 // Handle the case where there is a typing style.
2120 // FIXME: Improve typing style.
2121 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2122 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2123 if (typingStyle && typingStyle->length() > 0)
2124 nodeToInsert = applyTypingStyle(textNode);
2126 // Now insert the node in the right place
2127 if (pos.node()->isEditableBlock()) {
2128 LOG(Editing, "prepareForTextInsertion case 1");
2129 appendNode(nodeToInsert, pos.node());
2131 else if (pos.node()->caretMinOffset() == pos.offset()) {
2132 LOG(Editing, "prepareForTextInsertion case 2");
2133 insertNodeBefore(nodeToInsert, pos.node());
2135 else if (pos.node()->caretMaxOffset() == pos.offset()) {
2136 LOG(Editing, "prepareForTextInsertion case 3");
2137 insertNodeAfter(nodeToInsert, pos.node());
2140 ASSERT_NOT_REACHED();
2142 pos = Position(textNode, 0);
2145 // Handle the case where there is a typing style.
2146 // FIXME: Improve typing style.
2147 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2148 CSSStyleDeclarationImpl *typingStyle = document()->part()->typingStyle();
2149 if (typingStyle && typingStyle->length() > 0) {
2150 if (pos.node()->isTextNode() && pos.offset() > pos.node()->caretMinOffset() && pos.offset() < pos.node()->caretMaxOffset()) {
2151 // Need to split current text node in order to insert a span.
2152 TextImpl *text = static_cast<TextImpl *>(pos.node());
2153 SplitTextNodeCommand *impl = new SplitTextNodeCommand(document(), text, pos.offset());
2154 EditCommandPtr cmd(impl);
2155 applyCommandToComposite(cmd);
2156 setEndingSelection(Position(impl->node(), 0));
2159 TextImpl *editingTextNode = document()->createEditingTextNode("");
2160 NodeImpl *node = endingSelection().start().upstream(StayInBlock).node();
2161 if (node->isBlockFlow())
2162 insertNodeAt(applyTypingStyle(editingTextNode), node, 0);
2164 insertNodeAfter(applyTypingStyle(editingTextNode), node);
2165 pos = Position(editingTextNode, 0);
2171 void InputTextCommand::input(const DOMString &text, bool selectInsertedText)
2173 Selection selection = endingSelection();
2174 bool adjustDownstream = selection.start().downstream(StayInBlock).isFirstRenderedPositionOnLine();
2176 // Delete the current selection, or collapse whitespace, as needed
2177 if (selection.isRange())
2180 // Delete any insignificant text that could get in the way of whitespace turning
2181 // out correctly after the insertion.
2182 deleteInsignificantTextDownstream(endingSelection().end().trailingWhitespacePosition());
2184 // Make sure the document is set up to receive text
2185 Position pos = prepareForTextInsertion(adjustDownstream);
2187 TextImpl *textNode = static_cast<TextImpl *>(pos.node());
2188 long offset = pos.offset();
2190 // Now that we are about to add content, check to see if a placeholder element
2192 removeBlockPlaceholderIfNeeded(textNode->enclosingBlockFlowElement());
2194 // These are temporary implementations for inserting adjoining spaces
2195 // into a document. We are working on a CSS-related whitespace solution
2196 // that will replace this some day. We hope.
2198 // Treat a tab like a number of spaces. This seems to be the HTML editing convention,
2199 // although the number of spaces varies (we choose four spaces).
2200 // Note that there is no attempt to make this work like a real tab stop, it is merely
2201 // a set number of spaces. This also seems to be the HTML editing convention.
2202 for (int i = 0; i < spacesPerTab; i++) {
2203 insertSpace(textNode, offset);
2204 document()->updateLayout();
2206 if (selectInsertedText)
2207 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + spacesPerTab)));
2209 setEndingSelection(Position(textNode, offset + spacesPerTab));
2210 m_charactersAdded += spacesPerTab;
2212 else if (isWS(text)) {
2213 insertSpace(textNode, offset);
2214 if (selectInsertedText)
2215 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + 1)));
2217 setEndingSelection(Position(textNode, offset + 1));
2218 m_charactersAdded++;
2221 const DOMString &existingText = textNode->data();
2222 if (textNode->length() >= 2 && offset >= 2 && isNBSP(existingText[offset - 1]) && !isWS(existingText[offset - 2])) {
2223 // DOM looks like this:
2224 // character nbsp caret
2225 // As we are about to insert a non-whitespace character at the caret
2226 // convert the nbsp to a regular space.
2227 // EDIT FIXME: This needs to be improved some day to convert back only
2228 // those nbsp's added by the editor to make rendering come out right.
2229 replaceText(textNode, offset - 1, 1, " ");
2231 insertText(textNode, offset, text);
2232 if (selectInsertedText)
2233 setEndingSelection(Selection(Position(textNode, offset), Position(textNode, offset + text.length())));
2235 setEndingSelection(Position(textNode, offset + text.length()));
2236 m_charactersAdded += text.length();
2240 void InputTextCommand::insertSpace(TextImpl *textNode, unsigned long offset)
2244 DOMString text(textNode->data());
2246 // count up all spaces and newlines in front of the caret
2247 // delete all collapsed ones
2248 // this will work out OK since the offset we have been passed has been upstream-ized
2250 for (unsigned int i = offset; i < text.length(); i++) {
2257 // By checking the character at the downstream position, we can
2258 // check if there is a rendered WS at the caret
2259 Position pos(textNode, offset);
2260 Position downstream = pos.downstream();
2261 if (downstream.offset() < (long)text.length() && isWS(text[downstream.offset()]))
2262 count--; // leave this WS in
2264 deleteText(textNode, offset, count);
2267 if (offset > 0 && offset <= text.length() - 1 && !isWS(text[offset]) && !isWS(text[offset - 1])) {
2268 // insert a "regular" space
2269 insertText(textNode, offset, " ");
2273 if (text.length() >= 2 && offset >= 2 && isNBSP(text[offset - 2]) && isNBSP(text[offset - 1])) {
2274 // DOM looks like this:
2276 // insert a space between the two nbsps
2277 insertText(textNode, offset - 1, " ");
2282 insertText(textNode, offset, nonBreakingSpaceString());
2285 bool InputTextCommand::isInputTextCommand() const
2290 //------------------------------------------------------------------------------------------
2291 // InsertNodeBeforeCommand
2293 InsertNodeBeforeCommand::InsertNodeBeforeCommand(DocumentImpl *document, NodeImpl *insertChild, NodeImpl *refChild)
2294 : EditCommand(document), m_insertChild(insertChild), m_refChild(refChild)
2296 ASSERT(m_insertChild);
2297 m_insertChild->ref();
2303 InsertNodeBeforeCommand::~InsertNodeBeforeCommand()
2305 ASSERT(m_insertChild);
2306 m_insertChild->deref();
2309 m_refChild->deref();
2312 void InsertNodeBeforeCommand::doApply()
2314 ASSERT(m_insertChild);
2316 ASSERT(m_refChild->parentNode());
2318 int exceptionCode = 0;
2319 m_refChild->parentNode()->insertBefore(m_insertChild, m_refChild, exceptionCode);
2320 ASSERT(exceptionCode == 0);
2323 void InsertNodeBeforeCommand::doUnapply()
2325 ASSERT(m_insertChild);
2327 ASSERT(m_refChild->parentNode());
2329 int exceptionCode = 0;
2330 m_refChild->parentNode()->removeChild(m_insertChild, exceptionCode);
2331 ASSERT(exceptionCode == 0);
2334 //------------------------------------------------------------------------------------------
2335 // InsertTextCommand
2337 InsertTextCommand::InsertTextCommand(DocumentImpl *document, TextImpl *node, long offset, const DOMString &text)
2338 : EditCommand(document), m_node(node), m_offset(offset)
2341 ASSERT(m_offset >= 0);
2342 ASSERT(!text.isEmpty());
2345 m_text = text.copy(); // make a copy to ensure that the string never changes
2348 InsertTextCommand::~InsertTextCommand()
2354 void InsertTextCommand::doApply()
2357 ASSERT(m_offset >= 0);
2358 ASSERT(!m_text.isEmpty());
2360 int exceptionCode = 0;
2361 m_node->insertData(m_offset, m_text, exceptionCode);
2362 ASSERT(exceptionCode == 0);
2365 void InsertTextCommand::doUnapply()
2368 ASSERT(m_offset >= 0);
2369 ASSERT(!m_text.isEmpty());
2371 int exceptionCode = 0;
2372 m_node->deleteData(m_offset, m_text.length(), exceptionCode);
2373 ASSERT(exceptionCode == 0);
2376 //------------------------------------------------------------------------------------------
2377 // JoinTextNodesCommand
2379 JoinTextNodesCommand::JoinTextNodesCommand(DocumentImpl *document, TextImpl *text1, TextImpl *text2)
2380 : EditCommand(document), m_text1(text1), m_text2(text2)
2384 ASSERT(m_text1->nextSibling() == m_text2);
2385 ASSERT(m_text1->length() > 0);
2386 ASSERT(m_text2->length() > 0);
2392 JoinTextNodesCommand::~JoinTextNodesCommand()
2400 void JoinTextNodesCommand::doApply()
2404 ASSERT(m_text1->nextSibling() == m_text2);
2406 int exceptionCode = 0;
2407 m_text2->insertData(0, m_text1->data(), exceptionCode);
2408 ASSERT(exceptionCode == 0);
2410 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2411 ASSERT(exceptionCode == 0);
2413 m_offset = m_text1->length();
2416 void JoinTextNodesCommand::doUnapply()
2419 ASSERT(m_offset > 0);
2421 int exceptionCode = 0;
2423 m_text2->deleteData(0, m_offset, exceptionCode);
2424 ASSERT(exceptionCode == 0);
2426 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2427 ASSERT(exceptionCode == 0);
2429 ASSERT(m_text2->previousSibling()->isTextNode());
2430 ASSERT(m_text2->previousSibling() == m_text1);
2433 //------------------------------------------------------------------------------------------
2434 // ReplaceSelectionCommand
2436 ReplaceSelectionCommand::ReplaceSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, bool selectReplacement, bool smartReplace)
2437 : CompositeEditCommand(document), m_fragment(fragment), m_selectReplacement(selectReplacement), m_smartReplace(smartReplace)
2443 ReplaceSelectionCommand::~ReplaceSelectionCommand()
2446 m_fragment->deref();
2449 void ReplaceSelectionCommand::doApply()
2451 NodeImpl *firstChild = m_fragment->firstChild();
2452 NodeImpl *lastChild = m_fragment->lastChild();
2454 Selection selection = endingSelection();
2456 // Delete the current selection, or collapse whitespace, as needed
2457 if (selection.isRange())
2460 // This command does not use any typing style that is set as a residual effect of
2462 // FIXME: Improve typing style.
2463 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2464 document()->part()->clearTypingStyle();
2467 selection = endingSelection();
2468 ASSERT(selection.isCaret());
2470 // Now that we are about to add content, check to see if a placeholder element
2472 Position pos = selection.start();
2473 NodeImpl *block = pos.node()->enclosingBlockFlowElement();
2474 if (removeBlockPlaceholderIfNeeded(block)) {
2475 pos = Position(block, 0);
2478 bool addLeadingSpace = false;
2479 bool addTrailingSpace = false;
2480 if (m_smartReplace) {
2481 addLeadingSpace = pos.leadingWhitespacePosition().isNull();
2482 addTrailingSpace = pos.trailingWhitespacePosition().isNull();
2486 // Pasting something that didn't parse or was empty.
2488 } else if (firstChild == lastChild && firstChild->isTextNode()) {
2489 // FIXME: HTML fragment case needs to be improved to the point
2490 // where we can remove this separate case.
2492 // Simple text paste. Treat as if the text were typed.
2493 Position upstreamStart(pos.upstream(StayInBlock));
2494 DOMString text = static_cast<TextImpl *>(firstChild)->data();
2495 if (addLeadingSpace) {
2498 if (addTrailingSpace) {
2501 inputText(text, m_selectReplacement);
2504 // HTML fragment paste.
2506 // FIXME: Add leading and trailing spaces to the fragment?
2507 // Or just insert them as we insert it?
2509 NodeImpl *beforeNode = firstChild;
2510 NodeImpl *node = firstChild->nextSibling();
2512 insertNodeAt(firstChild, pos.node(), pos.offset());
2514 // Insert the nodes from the fragment
2516 NodeImpl *next = node->nextSibling();
2517 insertNodeAfter(node, beforeNode);
2523 // Find the last leaf.
2524 NodeImpl *lastLeaf = lastChild;
2526 NodeImpl *nextChild = lastLeaf->lastChild();
2529 lastLeaf = nextChild;
2532 // Find the first leaf.
2533 NodeImpl *firstLeaf = firstChild;
2535 NodeImpl *nextChild = firstLeaf->firstChild();
2538 firstLeaf = nextChild;
2541 Selection replacementSelection(Position(firstLeaf, firstLeaf->caretMinOffset()), Position(lastLeaf, lastLeaf->caretMaxOffset()));
2542 if (m_selectReplacement) {
2543 // Select what was inserted.
2544 setEndingSelection(replacementSelection);
2547 // Place the cursor after what was inserted, and mark misspellings in the inserted content.
2548 selection = Selection(Position(lastLeaf, lastLeaf->caretMaxOffset()));
2549 setEndingSelection(selection);
2554 //------------------------------------------------------------------------------------------
2555 // MoveSelectionCommand
2557 MoveSelectionCommand::MoveSelectionCommand(DocumentImpl *document, DocumentFragmentImpl *fragment, Position &position, bool smartMove)
2558 : CompositeEditCommand(document), m_fragment(fragment), m_position(position), m_smartMove(smartMove)
2564 MoveSelectionCommand::~MoveSelectionCommand()
2567 m_fragment->deref();
2570 void MoveSelectionCommand::doApply()
2572 Selection selection = endingSelection();
2573 ASSERT(selection.isRange());
2575 // Update the position otherwise it may become invalid after the selection is deleted.
2576 NodeImpl *positionNode = m_position.node();
2577 long positionOffset = m_position.offset();
2578 Position selectionEnd = selection.end();
2579 long selectionEndOffset = selectionEnd.offset();
2580 if (selectionEnd.node() == positionNode && selectionEndOffset < positionOffset) {
2581 positionOffset -= selectionEndOffset;
2582 Position selectionStart = selection.start();
2583 if (selectionStart.node() == positionNode) {
2584 positionOffset += selectionStart.offset();
2588 deleteSelection(m_smartMove);
2590 setEndingSelection(Position(positionNode, positionOffset));
2591 EditCommandPtr cmd(new ReplaceSelectionCommand(document(), m_fragment, true, m_smartMove));
2592 applyCommandToComposite(cmd);
2595 //------------------------------------------------------------------------------------------
2596 // RemoveCSSPropertyCommand
2598 RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(DocumentImpl *document, CSSStyleDeclarationImpl *decl, int property)
2599 : EditCommand(document), m_decl(decl), m_property(property), m_important(false)
2605 RemoveCSSPropertyCommand::~RemoveCSSPropertyCommand()
2611 void RemoveCSSPropertyCommand::doApply()
2615 m_oldValue = m_decl->getPropertyValue(m_property);
2616 ASSERT(!m_oldValue.isNull());
2618 m_important = m_decl->getPropertyPriority(m_property);
2619 m_decl->removeProperty(m_property);
2622 void RemoveCSSPropertyCommand::doUnapply()
2625 ASSERT(!m_oldValue.isNull());
2627 m_decl->setProperty(m_property, m_oldValue, m_important);
2630 //------------------------------------------------------------------------------------------
2631 // RemoveNodeAttributeCommand
2633 RemoveNodeAttributeCommand::RemoveNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute)
2634 : EditCommand(document), m_element(element), m_attribute(attribute)
2640 RemoveNodeAttributeCommand::~RemoveNodeAttributeCommand()
2646 void RemoveNodeAttributeCommand::doApply()
2650 m_oldValue = m_element->getAttribute(m_attribute);
2651 ASSERT(!m_oldValue.isNull());
2653 int exceptionCode = 0;
2654 m_element->removeAttribute(m_attribute, exceptionCode);
2655 ASSERT(exceptionCode == 0);
2658 void RemoveNodeAttributeCommand::doUnapply()
2661 ASSERT(!m_oldValue.isNull());
2663 int exceptionCode = 0;
2664 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2665 ASSERT(exceptionCode == 0);
2668 //------------------------------------------------------------------------------------------
2669 // RemoveNodeCommand
2671 RemoveNodeCommand::RemoveNodeCommand(DocumentImpl *document, NodeImpl *removeChild)
2672 : EditCommand(document), m_parent(0), m_removeChild(removeChild), m_refChild(0)
2674 ASSERT(m_removeChild);
2675 m_removeChild->ref();
2677 m_parent = m_removeChild->parentNode();
2681 m_refChild = m_removeChild->nextSibling();
2686 RemoveNodeCommand::~RemoveNodeCommand()
2691 ASSERT(m_removeChild);
2692 m_removeChild->deref();
2695 m_refChild->deref();
2698 void RemoveNodeCommand::doApply()
2701 ASSERT(m_removeChild);
2703 int exceptionCode = 0;
2704 m_parent->removeChild(m_removeChild, exceptionCode);
2705 ASSERT(exceptionCode == 0);
2708 void RemoveNodeCommand::doUnapply()
2711 ASSERT(m_removeChild);
2713 int exceptionCode = 0;
2714 m_parent->insertBefore(m_removeChild, m_refChild, exceptionCode);
2715 ASSERT(exceptionCode == 0);
2718 //------------------------------------------------------------------------------------------
2719 // RemoveNodePreservingChildrenCommand
2721 RemoveNodePreservingChildrenCommand::RemoveNodePreservingChildrenCommand(DocumentImpl *document, NodeImpl *node)
2722 : CompositeEditCommand(document), m_node(node)
2728 RemoveNodePreservingChildrenCommand::~RemoveNodePreservingChildrenCommand()
2734 void RemoveNodePreservingChildrenCommand::doApply()
2736 while (NodeImpl* curr = node()->firstChild()) {
2738 insertNodeBefore(curr, node());
2743 //------------------------------------------------------------------------------------------
2744 // SetNodeAttributeCommand
2746 SetNodeAttributeCommand::SetNodeAttributeCommand(DocumentImpl *document, ElementImpl *element, NodeImpl::Id attribute, const DOMString &value)
2747 : EditCommand(document), m_element(element), m_attribute(attribute), m_value(value)
2751 ASSERT(!m_value.isNull());
2754 SetNodeAttributeCommand::~SetNodeAttributeCommand()
2760 void SetNodeAttributeCommand::doApply()
2763 ASSERT(!m_value.isNull());
2765 int exceptionCode = 0;
2766 m_oldValue = m_element->getAttribute(m_attribute);
2767 m_element->setAttribute(m_attribute, m_value.implementation(), exceptionCode);
2768 ASSERT(exceptionCode == 0);
2771 void SetNodeAttributeCommand::doUnapply()
2774 ASSERT(!m_oldValue.isNull());
2776 int exceptionCode = 0;
2777 m_element->setAttribute(m_attribute, m_oldValue.implementation(), exceptionCode);
2778 ASSERT(exceptionCode == 0);
2781 //------------------------------------------------------------------------------------------
2782 // SplitTextNodeCommand
2784 SplitTextNodeCommand::SplitTextNodeCommand(DocumentImpl *document, TextImpl *text, long offset)
2785 : EditCommand(document), m_text1(0), m_text2(text), m_offset(offset)
2788 ASSERT(m_text2->length() > 0);
2793 SplitTextNodeCommand::~SplitTextNodeCommand()
2802 void SplitTextNodeCommand::doApply()
2805 ASSERT(m_offset > 0);
2807 int exceptionCode = 0;
2809 // EDIT FIXME: This should use better smarts for figuring out which portion
2810 // of the split to copy (based on their comparitive sizes). We should also
2811 // just use the DOM's splitText function.
2814 // create only if needed.
2815 // if reapplying, this object will already exist.
2816 m_text1 = document()->createTextNode(m_text2->substringData(0, m_offset, exceptionCode));
2817 ASSERT(exceptionCode == 0);
2822 m_text2->deleteData(0, m_offset, exceptionCode);
2823 ASSERT(exceptionCode == 0);
2825 m_text2->parentNode()->insertBefore(m_text1, m_text2, exceptionCode);
2826 ASSERT(exceptionCode == 0);
2828 ASSERT(m_text2->previousSibling()->isTextNode());
2829 ASSERT(m_text2->previousSibling() == m_text1);
2832 void SplitTextNodeCommand::doUnapply()
2837 ASSERT(m_text1->nextSibling() == m_text2);
2839 int exceptionCode = 0;
2840 m_text2->insertData(0, m_text1->data(), exceptionCode);
2841 ASSERT(exceptionCode == 0);
2843 m_text2->parentNode()->removeChild(m_text1, exceptionCode);
2844 ASSERT(exceptionCode == 0);
2846 m_offset = m_text1->length();
2849 //------------------------------------------------------------------------------------------
2852 TypingCommand::TypingCommand(DocumentImpl *document, ETypingCommand commandType, const DOMString &textToInsert, bool selectInsertedText)
2853 : CompositeEditCommand(document), m_commandType(commandType), m_textToInsert(textToInsert), m_openForMoreTyping(true), m_applyEditing(false), m_selectInsertedText(selectInsertedText)
2857 void TypingCommand::deleteKeyPressed(DocumentImpl *document)
2861 KHTMLPart *part = document->part();
2864 EditCommandPtr lastEditCommand = part->lastEditCommand();
2865 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2866 static_cast<TypingCommand *>(lastEditCommand.get())->deleteKeyPressed();
2869 EditCommandPtr cmd(new TypingCommand(document, DeleteKey));
2874 void TypingCommand::insertText(DocumentImpl *document, const DOMString &text, bool selectInsertedText)
2878 KHTMLPart *part = document->part();
2881 EditCommandPtr lastEditCommand = part->lastEditCommand();
2882 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2883 static_cast<TypingCommand *>(lastEditCommand.get())->insertText(text, selectInsertedText);
2886 EditCommandPtr cmd(new TypingCommand(document, InsertText, text, selectInsertedText));
2891 void TypingCommand::insertNewline(DocumentImpl *document)
2895 KHTMLPart *part = document->part();
2898 EditCommandPtr lastEditCommand = part->lastEditCommand();
2899 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2900 static_cast<TypingCommand *>(lastEditCommand.get())->insertNewline();
2903 EditCommandPtr cmd(new TypingCommand(document, InsertNewline));
2908 void TypingCommand::insertNewlineInQuotedContent(DocumentImpl *document)
2912 KHTMLPart *part = document->part();
2915 EditCommandPtr lastEditCommand = part->lastEditCommand();
2916 if (isOpenForMoreTypingCommand(lastEditCommand)) {
2917 static_cast<TypingCommand *>(lastEditCommand.get())->insertNewlineInQuotedContent();
2920 EditCommandPtr cmd(new TypingCommand(document, InsertNewlineInQuotedContent));
2925 bool TypingCommand::isOpenForMoreTypingCommand(const EditCommandPtr &cmd)
2927 return cmd.isTypingCommand() &&
2928 static_cast<const TypingCommand *>(cmd.get())->openForMoreTyping();
2931 void TypingCommand::closeTyping(const EditCommandPtr &cmd)
2933 if (isOpenForMoreTypingCommand(cmd))
2934 static_cast<TypingCommand *>(cmd.get())->closeTyping();
2937 void TypingCommand::doApply()
2939 if (endingSelection().isNone())
2942 switch (m_commandType) {
2947 insertText(m_textToInsert, m_selectInsertedText);
2952 case InsertNewlineInQuotedContent:
2953 insertNewlineInQuotedContent();
2957 ASSERT_NOT_REACHED();
2960 void TypingCommand::markMisspellingsAfterTyping()
2962 // Take a look at the selection that results after typing and determine whether we need to spellcheck.
2963 // Since the word containing the current selection is never marked, this does a check to
2964 // see if typing made a new word that is not in the current selection. Basically, you
2965 // get this by being at the end of a word and typing a space.
2966 VisiblePosition start(endingSelection().start());
2967 VisiblePosition previous = start.previous();
2968 if (previous.isNotNull()) {
2969 VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
2970 VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
2972 KWQ(document()->part())->markMisspellingsInAdjacentWords(p1);
2976 void TypingCommand::typingAddedToOpenCommand()
2978 markMisspellingsAfterTyping();
2979 // Do not apply editing to the part on the first time through.
2980 // The part will get told in the same way as all other commands.
2981 // But since this command stays open and is used for additional typing,
2982 // we need to tell the part here as other commands are added.
2983 if (m_applyEditing) {
2984 EditCommandPtr cmd(this);
2985 document()->part()->appliedEditing(cmd);
2987 m_applyEditing = true;
2990 void TypingCommand::insertText(const DOMString &text, bool selectInsertedText)
2992 // FIXME: Improve typing style.
2993 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2994 if (document()->part()->typingStyle() || m_cmds.count() == 0) {
2995 InputTextCommand *impl = new InputTextCommand(document());
2996 EditCommandPtr cmd(impl);
2997 applyCommandToComposite(cmd);
2998 impl->input(text, selectInsertedText);
3001 EditCommandPtr lastCommand = m_cmds.last();
3002 if (lastCommand.isInputTextCommand()) {
3003 InputTextCommand *impl = static_cast<InputTextCommand *>(lastCommand.get());
3004 impl->input(text, selectInsertedText);
3007 InputTextCommand *impl = new InputTextCommand(document());
3008 EditCommandPtr cmd(impl);
3009 applyCommandToComposite(cmd);
3010 impl->input(text, selectInsertedText);
3013 typingAddedToOpenCommand();
3016 void TypingCommand::insertNewline()
3018 EditCommandPtr cmd(new InputNewlineCommand(document()));
3019 applyCommandToComposite(cmd);
3020 typingAddedToOpenCommand();
3023 void TypingCommand::insertNewlineInQuotedContent()
3025 EditCommandPtr cmd(new InputNewlineInQuotedContentCommand(document()));
3026 applyCommandToComposite(cmd);
3027 typingAddedToOpenCommand();
3030 void TypingCommand::issueCommandForDeleteKey()
3032 Selection selectionToDelete;
3034 switch (endingSelection().state()) {
3035 case Selection::RANGE:
3036 selectionToDelete = endingSelection();
3038 case Selection::CARET: {
3039 // Handle delete at beginning-of-block case.
3040 // Do nothing in the case that the caret is at the start of a
3041 // root editable element or at the start of a document.
3042 Position pos(endingSelection().start());
3043 Position start = VisiblePosition(pos).previous().deepEquivalent();
3044 Position end = VisiblePosition(pos).deepEquivalent();
3045 if (start.isNotNull() && end.isNotNull() && start.node()->rootEditableElement() == end.node()->rootEditableElement())
3046 selectionToDelete = Selection(start, end);
3049 case Selection::NONE:
3050 ASSERT_NOT_REACHED();
3054 if (selectionToDelete.isCaretOrRange()) {
3055 deleteSelection(selectionToDelete);
3056 typingAddedToOpenCommand();
3060 void TypingCommand::deleteKeyPressed()
3062 // EDIT FIXME: The ifdef'ed out code below should be re-enabled.
3063 // In order for this to happen, the deleteCharacter case
3064 // needs work. Specifically, the caret-positioning code
3065 // and whitespace-handling code in DeleteSelectionCommand::doApply()
3066 // needs to be factored out so it can be used again here.
3067 // Until that work is done, issueCommandForDeleteKey() does the
3068 // right thing, but less efficiently and with the cost of more
3070 issueCommandForDeleteKey();
3072 if (m_cmds.count() == 0) {
3073 issueCommandForDeleteKey();
3076 EditCommandPtr lastCommand = m_cmds.last();
3077 if (lastCommand.isInputTextCommand()) {
3078 InputTextCommand &cmd = static_cast<InputTextCommand &>(lastCommand);
3079 cmd.deleteCharacter();
3080 if (cmd.charactersAdded() == 0) {
3081 removeCommand(lastCommand);
3084 else if (lastCommand.isInputNewlineCommand()) {
3085 lastCommand.unapply();
3086 removeCommand(lastCommand);
3089 issueCommandForDeleteKey();
3095 void TypingCommand::removeCommand(const EditCommandPtr &cmd)
3097 // NOTE: If the passed-in command is the last command in the
3098 // composite, we could remove all traces of this typing command
3099 // from the system, including the undo chain. Other editors do
3100 // not do this, but we could.
3103 if (m_cmds.count() == 0)
3104 setEndingSelection(startingSelection());
3106 setEndingSelection(m_cmds.last().endingSelection());
3109 bool TypingCommand::preservesTypingStyle() const
3111 switch (m_commandType) {
3116 case InsertNewlineInQuotedContent:
3119 ASSERT_NOT_REACHED();
3123 bool TypingCommand::isTypingCommand() const
3128 } // namespace khtml