Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(386)

Side by Side Diff: Source/core/editing/InsertParagraphSeparatorCommand.cpp

Issue 1294543005: Move execCommand related files in core/editing/ related files into core/editing/commands/ (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@master
Patch Set: 2015-08-17T17:57:33 Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
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.
12 *
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.
24 */
25
26 #include "config.h"
27 #include "core/editing/InsertParagraphSeparatorCommand.h"
28
29 #include "core/HTMLNames.h"
30 #include "core/dom/Document.h"
31 #include "core/dom/NodeTraversal.h"
32 #include "core/dom/Text.h"
33 #include "core/editing/EditingStyle.h"
34 #include "core/editing/EditingUtilities.h"
35 #include "core/editing/InsertLineBreakCommand.h"
36 #include "core/editing/VisibleUnits.h"
37 #include "core/html/HTMLBRElement.h"
38 #include "core/html/HTMLElement.h"
39 #include "core/html/HTMLQuoteElement.h"
40 #include "core/layout/LayoutObject.h"
41 #include "core/layout/LayoutText.h"
42
43 namespace blink {
44
45 using namespace HTMLNames;
46
47 // When inserting a new line, we want to avoid nesting empty divs if we can. Ot herwise, when
48 // pasting, it's easy to have each new line be a div deeper than the previous. E.g., in the case
49 // below, we want to insert at ^ instead of |.
50 // <div>foo<div>bar</div>|</div>^
51 static Element* highestVisuallyEquivalentDivBelowRoot(Element* startBlock)
52 {
53 Element* curBlock = startBlock;
54 // 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
55 // siblings for us to append to.
56 while (!curBlock->nextSibling() && isHTMLDivElement(*curBlock->parentElement ()) && curBlock->parentElement()->parentElement()) {
57 if (curBlock->parentElement()->hasAttributes())
58 break;
59 curBlock = curBlock->parentElement();
60 }
61 return curBlock;
62 }
63
64 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(Document& docum ent, bool mustUseDefaultParagraphElement, bool pasteBlockquoteIntoUnquotedArea)
65 : CompositeEditCommand(document)
66 , m_mustUseDefaultParagraphElement(mustUseDefaultParagraphElement)
67 , m_pasteBlockquoteIntoUnquotedArea(pasteBlockquoteIntoUnquotedArea)
68 {
69 }
70
71 bool InsertParagraphSeparatorCommand::preservesTypingStyle() const
72 {
73 return true;
74 }
75
76 void InsertParagraphSeparatorCommand::calculateStyleBeforeInsertion(const Positi on &pos)
77 {
78 // It is only important to set a style to apply later if we're at the bounda ries of
79 // a paragraph. Otherwise, content that is moved as part of the work of the command
80 // will lend their styles to the new paragraph without any extra work needed .
81 VisiblePosition visiblePos(pos, VP_DEFAULT_AFFINITY);
82 if (!isStartOfParagraph(visiblePos) && !isEndOfParagraph(visiblePos))
83 return;
84
85 ASSERT(pos.isNotNull());
86 m_style = EditingStyle::create(pos);
87 m_style->mergeTypingStyle(pos.document());
88 }
89
90 void InsertParagraphSeparatorCommand::applyStyleAfterInsertion(Element* original EnclosingBlock)
91 {
92 // Not only do we break out of header tags, but we also do not preserve the typing style,
93 // in order to match other browsers.
94 if (originalEnclosingBlock->hasTagName(h1Tag) ||
95 originalEnclosingBlock->hasTagName(h2Tag) ||
96 originalEnclosingBlock->hasTagName(h3Tag) ||
97 originalEnclosingBlock->hasTagName(h4Tag) ||
98 originalEnclosingBlock->hasTagName(h5Tag))
99 return;
100
101 if (!m_style)
102 return;
103
104 m_style->prepareToApplyAt(endingSelection().start());
105 if (!m_style->isEmpty())
106 applyStyle(m_style.get());
107 }
108
109 bool InsertParagraphSeparatorCommand::shouldUseDefaultParagraphElement(Element* enclosingBlock) const
110 {
111 if (m_mustUseDefaultParagraphElement)
112 return true;
113
114 // Assumes that if there was a range selection, it was already deleted.
115 if (!isEndOfBlock(endingSelection().visibleStart()))
116 return false;
117
118 return enclosingBlock->hasTagName(h1Tag) ||
119 enclosingBlock->hasTagName(h2Tag) ||
120 enclosingBlock->hasTagName(h3Tag) ||
121 enclosingBlock->hasTagName(h4Tag) ||
122 enclosingBlock->hasTagName(h5Tag);
123 }
124
125 void InsertParagraphSeparatorCommand::getAncestorsInsideBlock(const Node* insert ionNode, Element* outerBlock, WillBeHeapVector<RefPtrWillBeMember<Element>>& anc estors)
126 {
127 ancestors.clear();
128
129 // Build up list of ancestors elements between the insertion node and the ou ter block.
130 if (insertionNode != outerBlock) {
131 for (Element* n = insertionNode->parentElement(); n && n != outerBlock; n = n->parentElement())
132 ancestors.append(n);
133 }
134 }
135
136 PassRefPtrWillBeRawPtr<Element> InsertParagraphSeparatorCommand::cloneHierarchyU nderNewBlock(const WillBeHeapVector<RefPtrWillBeMember<Element>>& ancestors, Pas sRefPtrWillBeRawPtr<Element> blockToInsert)
137 {
138 // Make clones of ancestors in between the start node and the start block.
139 RefPtrWillBeRawPtr<Element> parent = blockToInsert;
140 for (size_t i = ancestors.size(); i != 0; --i) {
141 RefPtrWillBeRawPtr<Element> child = ancestors[i - 1]->cloneElementWithou tChildren();
142 // It should always be okay to remove id from the cloned elements, since the originals are not deleted.
143 child->removeAttribute(idAttr);
144 appendNode(child, parent);
145 parent = child.release();
146 }
147
148 return parent.release();
149 }
150
151 void InsertParagraphSeparatorCommand::doApply()
152 {
153 if (!endingSelection().isNonOrphanedCaretOrRange())
154 return;
155
156 Position insertionPosition = endingSelection().start();
157
158 EAffinity affinity = endingSelection().affinity();
159
160 // Delete the current selection.
161 if (endingSelection().isRange()) {
162 calculateStyleBeforeInsertion(insertionPosition);
163 deleteSelection(false, true);
164 insertionPosition = endingSelection().start();
165 affinity = endingSelection().affinity();
166 }
167
168 // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enc losingBlock.
169 RefPtrWillBeRawPtr<Element> startBlock = enclosingBlock(insertionPosition.pa rentAnchoredEquivalent().computeContainerNode());
170 Node* listChildNode = enclosingListChild(insertionPosition.parentAnchoredEqu ivalent().computeContainerNode());
171 RefPtrWillBeRawPtr<HTMLElement> listChild = listChildNode && listChildNode-> isHTMLElement() ? toHTMLElement(listChildNode) : 0;
172 Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
173 if (!startBlock
174 || !startBlock->nonShadowBoundaryParentNode()
175 || isTableCell(startBlock.get())
176 || isHTMLFormElement(*startBlock)
177 // FIXME: If the node is hidden, we don't have a canonical position so w e will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug. cgi?id=40342
178 || (!canonicalPos.isNull() && isRenderedTableElement(canonicalPos.anchor Node()))
179 || (!canonicalPos.isNull() && isHTMLHRElement(*canonicalPos.anchorNode() ))) {
180 applyCommandToComposite(InsertLineBreakCommand::create(document()));
181 return;
182 }
183
184 // Use the leftmost candidate.
185 insertionPosition = insertionPosition.upstream();
186 if (!insertionPosition.isCandidate())
187 insertionPosition = insertionPosition.downstream();
188
189 // Adjust the insertion position after the delete
190 insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition );
191 VisiblePosition visiblePos(insertionPosition, affinity);
192 calculateStyleBeforeInsertion(insertionPosition);
193
194 //---------------------------------------------------------------------
195 // Handle special case of typing return on an empty list item
196 if (breakOutOfEmptyListItem())
197 return;
198
199 //---------------------------------------------------------------------
200 // Prepare for more general cases.
201
202 bool isFirstInBlock = isStartOfBlock(visiblePos);
203 bool isLastInBlock = isEndOfBlock(visiblePos);
204 bool nestNewBlock = false;
205
206 // Create block to be inserted.
207 RefPtrWillBeRawPtr<Element> blockToInsert = nullptr;
208 if (startBlock->isRootEditableElement()) {
209 blockToInsert = createDefaultParagraphElement(document());
210 nestNewBlock = true;
211 } else if (shouldUseDefaultParagraphElement(startBlock.get())) {
212 blockToInsert = createDefaultParagraphElement(document());
213 } else {
214 blockToInsert = startBlock->cloneElementWithoutChildren();
215 }
216
217 //---------------------------------------------------------------------
218 // Handle case when position is in the last visible position in its block,
219 // including when the block is empty.
220 if (isLastInBlock) {
221 if (nestNewBlock) {
222 if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
223 // The block is empty. Create an empty block to
224 // represent the paragraph that we're leaving.
225 RefPtrWillBeRawPtr<HTMLElement> extraBlock = createDefaultParagr aphElement(document());
226 appendNode(extraBlock, startBlock);
227 appendBlockPlaceholder(extraBlock);
228 }
229 appendNode(blockToInsert, startBlock);
230 } else {
231 // We can get here if we pasted a copied portion of a blockquote wit h a newline at the end and are trying to paste it
232 // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
233 if (m_pasteBlockquoteIntoUnquotedArea) {
234 if (HTMLQuoteElement* highestBlockquote = toHTMLQuoteElement(hig hestEnclosingNodeOfType(canonicalPos, &isMailHTMLBlockquoteElement)))
235 startBlock = highestBlockquote;
236 }
237
238 if (listChild && listChild != startBlock) {
239 RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->clone ElementWithoutChildren();
240 appendNode(blockToInsert, listChildToInsert.get());
241 insertNodeAfter(listChildToInsert.get(), listChild);
242 } else {
243 // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists). However,
244 // for div nodes, this can result in nested div tags that are ha rd to break out of.
245 Element* siblingElement = startBlock.get();
246 if (isHTMLDivElement(*blockToInsert))
247 siblingElement = highestVisuallyEquivalentDivBelowRoot(start Block.get());
248 insertNodeAfter(blockToInsert, siblingElement);
249 }
250 }
251
252 // Recreate the same structure in the new paragraph.
253
254 WillBeHeapVector<RefPtrWillBeMember<Element>> ancestors;
255 getAncestorsInsideBlock(positionOutsideTabSpan(insertionPosition).anchor Node(), startBlock.get(), ancestors);
256 RefPtrWillBeRawPtr<Element> parent = cloneHierarchyUnderNewBlock(ancesto rs, blockToInsert);
257
258 appendBlockPlaceholder(parent);
259
260 setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), D OWNSTREAM, endingSelection().isDirectional()));
261 return;
262 }
263
264
265 //---------------------------------------------------------------------
266 // Handle case when position is in the first visible position in its block, and
267 // similar case where previous position is in another, presumeably nested, b lock.
268 if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
269 Node* refNode = nullptr;
270 insertionPosition = positionOutsideTabSpan(insertionPosition);
271
272 if (isFirstInBlock && !nestNewBlock) {
273 if (listChild && listChild != startBlock) {
274 RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->clone ElementWithoutChildren();
275 appendNode(blockToInsert, listChildToInsert.get());
276 insertNodeBefore(listChildToInsert.get(), listChild);
277 } else {
278 refNode = startBlock.get();
279 }
280 } else if (isFirstInBlock && nestNewBlock) {
281 // startBlock should always have children, otherwise isLastInBlock w ould be true and it's handled above.
282 ASSERT(startBlock->hasChildren());
283 refNode = startBlock->firstChild();
284 } else if (insertionPosition.anchorNode() == startBlock && nestNewBlock) {
285 refNode = NodeTraversal::childAt(*startBlock, insertionPosition.comp uteEditingOffset());
286 ASSERT(refNode); // must be true or we'd be in the end of block case
287 } else {
288 refNode = insertionPosition.anchorNode();
289 }
290
291 // find ending selection position easily before inserting the paragraph
292 insertionPosition = insertionPosition.downstream();
293
294 if (refNode)
295 insertNodeBefore(blockToInsert, refNode);
296
297 // Recreate the same structure in the new paragraph.
298
299 WillBeHeapVector<RefPtrWillBeMember<Element>> ancestors;
300 getAncestorsInsideBlock(positionAvoidingSpecialElementBoundary(positionO utsideTabSpan(insertionPosition)).anchorNode(), startBlock.get(), ancestors);
301
302 appendBlockPlaceholder(cloneHierarchyUnderNewBlock(ancestors, blockToIns ert));
303
304 // In this case, we need to set the new ending selection.
305 setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endin gSelection().isDirectional()));
306 return;
307 }
308
309 //---------------------------------------------------------------------
310 // Handle the (more complicated) general case,
311
312 // All of the content in the current block after visiblePos is
313 // about to be wrapped in a new paragraph element. Add a br before
314 // it if visiblePos is at the start of a paragraph so that the
315 // content will move down a line.
316 if (isStartOfParagraph(visiblePos)) {
317 RefPtrWillBeRawPtr<HTMLBRElement> br = createBreakElement(document());
318 insertNodeAt(br.get(), insertionPosition);
319 insertionPosition = positionInParentAfterNode(*br);
320 // If the insertion point is a break element, there is nothing else
321 // we need to do.
322 if (visiblePos.deepEquivalent().anchorNode()->layoutObject()->isBR()) {
323 setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, e ndingSelection().isDirectional()));
324 return;
325 }
326 }
327
328 // Move downstream. Typing style code will take care of carrying along the
329 // style of the upstream position.
330 insertionPosition = insertionPosition.downstream();
331
332 // At this point, the insertionPosition's node could be a container, and we want to make sure we include
333 // all of the correct nodes when building the ancestor list. So this needs to be the deepest representation of the position
334 // before we walk the DOM tree.
335 insertionPosition = positionOutsideTabSpan(VisiblePosition(insertionPosition ).deepEquivalent());
336
337 // If the returned position lies either at the end or at the start of an ele ment that is ignored by editing
338 // we should move to its upstream or downstream position.
339 if (editingIgnoresContent(insertionPosition.anchorNode())) {
340 if (insertionPosition.atLastEditingPositionForNode())
341 insertionPosition = insertionPosition.downstream();
342 else if (insertionPosition.atFirstEditingPositionForNode())
343 insertionPosition = insertionPosition.upstream();
344 }
345
346 // Make sure we do not cause a rendered space to become unrendered.
347 // FIXME: We need the affinity for pos, but pos.downstream() does not give i t
348 Position leadingWhitespace = leadingWhitespacePosition(insertionPosition, VP _DEFAULT_AFFINITY);
349 // FIXME: leadingWhitespacePosition is returning the position before preserv ed newlines for positions
350 // after the preserved newline, causing the newline to be turned into a nbsp .
351 if (leadingWhitespace.isNotNull() && leadingWhitespace.anchorNode()->isTextN ode()) {
352 Text* textNode = toText(leadingWhitespace.anchorNode());
353 ASSERT(!textNode->layoutObject() || textNode->layoutObject()->style()->c ollapseWhiteSpace());
354 replaceTextInNodePreservingMarkers(textNode, leadingWhitespace.computeOf fsetInContainerNode(), 1, nonBreakingSpaceString());
355 }
356
357 // Split at pos if in the middle of a text node.
358 Position positionAfterSplit;
359 if (insertionPosition.isOffsetInAnchor() && insertionPosition.computeContain erNode()->isTextNode()) {
360 RefPtrWillBeRawPtr<Text> textNode = toText(insertionPosition.computeCont ainerNode());
361 int textOffset = insertionPosition.offsetInContainerNode();
362 bool atEnd = static_cast<unsigned>(textOffset) >= textNode->length();
363 if (textOffset > 0 && !atEnd) {
364 splitTextNode(textNode, textOffset);
365 positionAfterSplit = firstPositionInNode(textNode.get());
366 insertionPosition = Position(textNode->previousSibling(), textOffset );
367 visiblePos = VisiblePosition(insertionPosition);
368 }
369 }
370
371 // If we got detached due to mutation events, just bail out.
372 if (!startBlock->parentNode())
373 return;
374
375 // Put the added block in the tree.
376 if (nestNewBlock) {
377 appendNode(blockToInsert.get(), startBlock);
378 } else if (listChild && listChild != startBlock) {
379 RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->cloneElementW ithoutChildren();
380 appendNode(blockToInsert.get(), listChildToInsert.get());
381 insertNodeAfter(listChildToInsert.get(), listChild);
382 } else {
383 insertNodeAfter(blockToInsert.get(), startBlock);
384 }
385
386 document().updateLayoutIgnorePendingStylesheets();
387
388 // If the paragraph separator was inserted at the end of a paragraph, an emp ty line must be
389 // created. All of the nodes, starting at visiblePos, are about to be added to the new paragraph
390 // element. If the first node to be inserted won't be one that will hold an empty line open, add a br.
391 if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visibl ePos))
392 appendNode(createBreakElement(document()).get(), blockToInsert.get());
393
394 // Move the start node and the siblings of the start node.
395 if (VisiblePosition(insertionPosition).deepEquivalent() != VisiblePosition(p ositionBeforeNode(blockToInsert.get())).deepEquivalent()) {
396 Node* n;
397 if (insertionPosition.computeContainerNode() == startBlock)
398 n = insertionPosition.computeNodeAfterPosition();
399 else {
400 Node* splitTo = insertionPosition.computeContainerNode();
401 if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode () >= caretMaxOffset(splitTo))
402 splitTo = NodeTraversal::next(*splitTo, startBlock.get());
403 ASSERT(splitTo);
404 splitTreeToNode(splitTo, startBlock.get());
405
406 for (n = startBlock->firstChild(); n; n = n->nextSibling()) {
407 VisiblePosition beforeNodePosition(positionBeforeNode(n));
408 if (!beforeNodePosition.isNull() && comparePositions(VisiblePosi tion(insertionPosition), beforeNodePosition) <= 0)
409 break;
410 }
411 }
412
413 moveRemainingSiblingsToNewParent(n, blockToInsert.get(), blockToInsert);
414 }
415
416 // Handle whitespace that occurs after the split
417 if (positionAfterSplit.isNotNull()) {
418 document().updateLayoutIgnorePendingStylesheets();
419 if (!positionAfterSplit.isRenderedCharacter()) {
420 // Clear out all whitespace and insert one non-breaking space
421 ASSERT(!positionAfterSplit.computeContainerNode()->layoutObject() || positionAfterSplit.computeContainerNode()->layoutObject()->style()->collapseWhi teSpace());
422 deleteInsignificantTextDownstream(positionAfterSplit);
423 if (positionAfterSplit.anchorNode()->isTextNode())
424 insertTextIntoNode(toText(positionAfterSplit.computeContainerNod e()), 0, nonBreakingSpaceString());
425 }
426 }
427
428 setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()) , DOWNSTREAM, endingSelection().isDirectional()));
429 applyStyleAfterInsertion(startBlock.get());
430 }
431
432 DEFINE_TRACE(InsertParagraphSeparatorCommand)
433 {
434 visitor->trace(m_style);
435 CompositeEditCommand::trace(visitor);
436 }
437
438
439 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698