2 * Copyright (C) 2005, 2006 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.
27 #include "InsertParagraphSeparatorCommand.h"
29 #include "CSSPropertyNames.h"
31 #include "EditingStyle.h"
32 #include "HTMLElement.h"
33 #include "HTMLNames.h"
34 #include "InsertLineBreakCommand.h"
35 #include "RenderObject.h"
37 #include "htmlediting.h"
38 #include "visible_units.h"
42 using namespace HTMLNames;
44 // When inserting a new line, we want to avoid nesting empty divs if we can. Otherwise, when
45 // pasting, it's easy to have each new line be a div deeper than the previous. E.g., in the case
46 // below, we want to insert at ^ instead of |.
47 // <div>foo<div>bar</div>|</div>^
48 static Element* highestVisuallyEquivalentDivBelowRoot(Element* startBlock)
50 Element* curBlock = startBlock;
51 // We don't want to return a root node (if it happens to be a div, e.g., in a document fragment) because there are no
52 // siblings for us to append to.
53 while (!curBlock->nextSibling() && curBlock->parentElement()->hasTagName(divTag) && curBlock->parentElement()->parentElement()) {
54 NamedNodeMap* attributes = curBlock->parentElement()->attributes(true);
55 if (attributes && !attributes->isEmpty())
57 curBlock = curBlock->parentElement();
62 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(Document *document, bool mustUseDefaultParagraphElement)
63 : CompositeEditCommand(document)
64 , m_mustUseDefaultParagraphElement(mustUseDefaultParagraphElement)
68 bool InsertParagraphSeparatorCommand::preservesTypingStyle() const
73 void InsertParagraphSeparatorCommand::calculateStyleBeforeInsertion(const Position &pos)
75 // It is only important to set a style to apply later if we're at the boundaries of
76 // a paragraph. Otherwise, content that is moved as part of the work of the command
77 // will lend their styles to the new paragraph without any extra work needed.
78 VisiblePosition visiblePos(pos, VP_DEFAULT_AFFINITY);
79 if (!isStartOfParagraph(visiblePos) && !isEndOfParagraph(visiblePos))
82 ASSERT(pos.isNotNull());
83 m_style = EditingStyle::create(pos);
84 m_style->mergeTypingStyle(pos.anchorNode()->document());
87 void InsertParagraphSeparatorCommand::applyStyleAfterInsertion(Node* originalEnclosingBlock)
89 // Not only do we break out of header tags, but we also do not preserve the typing style,
90 // in order to match other browsers.
91 if (originalEnclosingBlock->hasTagName(h1Tag) ||
92 originalEnclosingBlock->hasTagName(h2Tag) ||
93 originalEnclosingBlock->hasTagName(h3Tag) ||
94 originalEnclosingBlock->hasTagName(h4Tag) ||
95 originalEnclosingBlock->hasTagName(h5Tag))
101 m_style->prepareToApplyAt(endingSelection().start());
102 if (!m_style->isEmpty())
103 applyStyle(m_style.get());
106 bool InsertParagraphSeparatorCommand::shouldUseDefaultParagraphElement(Node* enclosingBlock) const
108 if (m_mustUseDefaultParagraphElement)
111 // Assumes that if there was a range selection, it was already deleted.
112 if (!isEndOfBlock(endingSelection().visibleStart()))
115 return enclosingBlock->hasTagName(h1Tag) ||
116 enclosingBlock->hasTagName(h2Tag) ||
117 enclosingBlock->hasTagName(h3Tag) ||
118 enclosingBlock->hasTagName(h4Tag) ||
119 enclosingBlock->hasTagName(h5Tag);
122 void InsertParagraphSeparatorCommand::getAncestorsInsideBlock(const Node* insertionNode, Element* outerBlock, Vector<Element*>& ancestors)
126 // Build up list of ancestors elements between the insertion node and the outer block.
127 if (insertionNode != outerBlock) {
128 for (Element* n = insertionNode->parentElement(); n && n != outerBlock; n = n->parentElement())
133 PassRefPtr<Element> InsertParagraphSeparatorCommand::cloneHierarchyUnderNewBlock(const Vector<Element*>& ancestors, PassRefPtr<Element> blockToInsert)
135 // Make clones of ancestors in between the start node and the start block.
136 RefPtr<Element> parent = blockToInsert;
137 for (size_t i = ancestors.size(); i != 0; --i) {
138 RefPtr<Element> child = ancestors[i - 1]->cloneElementWithoutChildren();
139 appendNode(child, parent);
140 parent = child.release();
143 return parent.release();
146 void InsertParagraphSeparatorCommand::doApply()
148 bool splitText = false;
149 if (!endingSelection().isNonOrphanedCaretOrRange())
152 Position insertionPosition = endingSelection().start();
154 EAffinity affinity = endingSelection().affinity();
156 // Delete the current selection.
157 if (endingSelection().isRange()) {
158 calculateStyleBeforeInsertion(insertionPosition);
159 deleteSelection(false, true);
160 insertionPosition = endingSelection().start();
161 affinity = endingSelection().affinity();
164 // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enclosingBlock.
165 Node* startBlockNode = enclosingBlock(insertionPosition.parentAnchoredEquivalent().containerNode());
166 Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
167 Element* startBlock = static_cast<Element*>(startBlockNode);
169 || !startBlockNode->isElementNode()
170 || !startBlock->parentNode()
171 || isTableCell(startBlock)
172 || startBlock->hasTagName(formTag)
173 // FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
174 || (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->renderer() && canonicalPos.deprecatedNode()->renderer()->isTable())
175 || (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->hasTagName(hrTag))) {
176 applyCommandToComposite(InsertLineBreakCommand::create(document()));
180 // Use the leftmost candidate.
181 insertionPosition = insertionPosition.upstream();
182 if (!insertionPosition.isCandidate())
183 insertionPosition = insertionPosition.downstream();
185 // Adjust the insertion position after the delete
186 insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition);
187 VisiblePosition visiblePos(insertionPosition, affinity);
188 calculateStyleBeforeInsertion(insertionPosition);
190 //---------------------------------------------------------------------
191 // Handle special case of typing return on an empty list item
192 if (breakOutOfEmptyListItem())
195 //---------------------------------------------------------------------
196 // Prepare for more general cases.
198 bool isFirstInBlock = isStartOfBlock(visiblePos);
199 bool isLastInBlock = isEndOfBlock(visiblePos);
200 bool nestNewBlock = false;
202 // Create block to be inserted.
203 RefPtr<Element> blockToInsert;
204 if (startBlock == startBlock->rootEditableElement()) {
205 blockToInsert = createDefaultParagraphElement(document());
207 } else if (shouldUseDefaultParagraphElement(startBlock))
208 blockToInsert = createDefaultParagraphElement(document());
210 blockToInsert = startBlock->cloneElementWithoutChildren();
212 //---------------------------------------------------------------------
213 // Handle case when position is in the last visible position in its block,
214 // including when the block is empty.
217 if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
218 // The block is empty. Create an empty block to
219 // represent the paragraph that we're leaving.
220 RefPtr<Element> extraBlock = createDefaultParagraphElement(document());
221 appendNode(extraBlock, startBlock);
222 appendBlockPlaceholder(extraBlock);
224 appendNode(blockToInsert, startBlock);
226 // We can get here if we pasted a copied portion of a blockquote with a newline at the end and are trying to paste it
227 // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
228 if (Node* highestBlockquote = highestEnclosingNodeOfType(canonicalPos, &isMailBlockquote))
229 startBlock = static_cast<Element*>(highestBlockquote);
231 // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists). However,
232 // for div nodes, this can result in nested div tags that are hard to break out of.
233 Element* siblingNode = startBlock;
234 if (blockToInsert->hasTagName(divTag))
235 siblingNode = highestVisuallyEquivalentDivBelowRoot(startBlock);
236 insertNodeAfter(blockToInsert, siblingNode);
239 // Recreate the same structure in the new paragraph.
241 Vector<Element*> ancestors;
242 getAncestorsInsideBlock(insertionPosition.deprecatedNode(), startBlock, ancestors);
243 RefPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert);
245 appendBlockPlaceholder(parent);
247 setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), DOWNSTREAM));
252 //---------------------------------------------------------------------
253 // Handle case when position is in the first visible position in its block, and
254 // similar case where previous position is in another, presumeably nested, block.
255 if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
257 if (isFirstInBlock && !nestNewBlock)
258 refNode = startBlock;
259 else if (insertionPosition.deprecatedNode() == startBlock && nestNewBlock) {
260 refNode = startBlock->childNode(insertionPosition.deprecatedEditingOffset());
261 ASSERT(refNode); // must be true or we'd be in the end of block case
263 refNode = insertionPosition.deprecatedNode();
265 // find ending selection position easily before inserting the paragraph
266 insertionPosition = insertionPosition.downstream();
268 insertNodeBefore(blockToInsert, refNode);
270 // Recreate the same structure in the new paragraph.
272 Vector<Element*> ancestors;
273 getAncestorsInsideBlock(positionAvoidingSpecialElementBoundary(insertionPosition).deprecatedNode(), startBlock, ancestors);
275 appendBlockPlaceholder(cloneHierarchyUnderNewBlock(ancestors, blockToInsert));
277 // In this case, we need to set the new ending selection.
278 setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM));
282 //---------------------------------------------------------------------
283 // Handle the (more complicated) general case,
285 // All of the content in the current block after visiblePos is
286 // about to be wrapped in a new paragraph element. Add a br before
287 // it if visiblePos is at the start of a paragraph so that the
288 // content will move down a line.
289 if (isStartOfParagraph(visiblePos)) {
290 RefPtr<Element> br = createBreakElement(document());
291 insertNodeAt(br.get(), insertionPosition);
292 insertionPosition = positionInParentAfterNode(br.get());
295 // Move downstream. Typing style code will take care of carrying along the
296 // style of the upstream position.
297 insertionPosition = insertionPosition.downstream();
299 // At this point, the insertionPosition's node could be a container, and we want to make sure we include
300 // all of the correct nodes when building the ancestor list. So this needs to be the deepest representation of the position
301 // before we walk the DOM tree.
302 insertionPosition = VisiblePosition(insertionPosition).deepEquivalent();
304 // Build up list of ancestors in between the start node and the start block.
305 Vector<Element*> ancestors;
306 getAncestorsInsideBlock(insertionPosition.deprecatedNode(), startBlock, ancestors);
308 // Make sure we do not cause a rendered space to become unrendered.
309 // FIXME: We need the affinity for pos, but pos.downstream() does not give it
310 Position leadingWhitespace = insertionPosition.leadingWhitespacePosition(VP_DEFAULT_AFFINITY);
311 // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
312 // after the preserved newline, causing the newline to be turned into a nbsp.
313 if (leadingWhitespace.isNotNull() && leadingWhitespace.deprecatedNode()->isTextNode()) {
314 Text* textNode = static_cast<Text*>(leadingWhitespace.deprecatedNode());
315 ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
316 replaceTextInNode(textNode, leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
319 // Split at pos if in the middle of a text node.
320 if (insertionPosition.deprecatedNode()->isTextNode()) {
321 Text* textNode = static_cast<Text*>(insertionPosition.deprecatedNode());
322 bool atEnd = (unsigned)insertionPosition.deprecatedEditingOffset() >= textNode->length();
323 if (insertionPosition.deprecatedEditingOffset() > 0 && !atEnd) {
324 splitTextNode(textNode, insertionPosition.deprecatedEditingOffset());
325 insertionPosition.moveToOffset(0);
326 visiblePos = VisiblePosition(insertionPosition);
331 // Put the added block in the tree.
333 appendNode(blockToInsert.get(), startBlock);
335 insertNodeAfter(blockToInsert.get(), startBlock);
339 // Make clones of ancestors in between the start node and the outer block.
340 RefPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert);
342 // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
343 // created. All of the nodes, starting at visiblePos, are about to be added to the new paragraph
344 // element. If the first node to be inserted won't be one that will hold an empty line open, add a br.
345 if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visiblePos))
346 appendNode(createBreakElement(document()).get(), blockToInsert.get());
348 // Move the start node and the siblings of the start node.
349 if (insertionPosition.deprecatedNode() != startBlock) {
350 Node* n = insertionPosition.deprecatedNode();
351 if (insertionPosition.deprecatedEditingOffset() >= caretMaxOffset(n))
352 n = n->nextSibling();
354 while (n && n != blockToInsert) {
355 Node *next = n->nextSibling();
357 appendNode(n, parent.get());
362 // Move everything after the start node.
363 if (!ancestors.isEmpty()) {
364 Element* leftParent = ancestors.first();
365 while (leftParent && leftParent != startBlock) {
366 parent = parent->parentElement();
369 Node* n = leftParent->nextSibling();
370 while (n && n != blockToInsert) {
371 Node* next = n->nextSibling();
373 appendNode(n, parent.get());
376 leftParent = leftParent->parentElement();
380 // Handle whitespace that occurs after the split
383 if (insertionPosition.anchorType() == Position::PositionIsOffsetInAnchor)
384 insertionPosition.moveToOffset(0);
385 if (!insertionPosition.isRenderedCharacter()) {
386 // Clear out all whitespace and insert one non-breaking space
387 ASSERT(!insertionPosition.deprecatedNode()->renderer() || insertionPosition.deprecatedNode()->renderer()->style()->collapseWhiteSpace());
388 deleteInsignificantTextDownstream(insertionPosition);
389 if (insertionPosition.deprecatedNode()->isTextNode())
390 insertTextIntoNode(static_cast<Text*>(insertionPosition.deprecatedNode()), 0, nonBreakingSpaceString());
394 setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()), DOWNSTREAM));
395 applyStyleAfterInsertion(startBlock);
398 } // namespace WebCore