[iOS] Upstream WebCore and Tools miscellaneous changes
[WebKit-https.git] / Source / WebCore / editing / Editor.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2011, 2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "Editor.h"
29
30 #include "AXObjectCache.h"
31 #include "AlternativeTextController.h"
32 #include "ApplyStyleCommand.h"
33 #include "CSSComputedStyleDeclaration.h"
34 #include "CSSPropertyNames.h"
35 #include "CachedResourceLoader.h"
36 #include "Clipboard.h"
37 #include "ClipboardEvent.h"
38 #include "CompositionEvent.h"
39 #include "CreateLinkCommand.h"
40 #include "DeleteSelectionCommand.h"
41 #include "DictationAlternative.h"
42 #include "DictationCommand.h"
43 #include "DocumentFragment.h"
44 #include "DocumentMarkerController.h"
45 #include "EditorClient.h"
46 #include "EventHandler.h"
47 #include "EventNames.h"
48 #include "ExceptionCodePlaceholder.h"
49 #include "FocusController.h"
50 #include "Frame.h"
51 #include "FrameTree.h"
52 #include "FrameView.h"
53 #include "GraphicsContext.h"
54 #include "HTMLFormControlElement.h"
55 #include "HTMLFrameOwnerElement.h"
56 #include "HTMLImageElement.h"
57 #include "HTMLNames.h"
58 #include "HTMLTextAreaElement.h"
59 #include "HitTestResult.h"
60 #include "IndentOutdentCommand.h"
61 #include "InsertListCommand.h"
62 #include "KeyboardEvent.h"
63 #include "KillRing.h"
64 #include "ModifySelectionListLevel.h"
65 #include "NodeList.h"
66 #include "NodeTraversal.h"
67 #include "Page.h"
68 #include "Pasteboard.h"
69 #include "RemoveFormatCommand.h"
70 #include "RenderBlock.h"
71 #include "RenderTextControl.h"
72 #include "RenderedPosition.h"
73 #include "ReplaceSelectionCommand.h"
74 #include "Settings.h"
75 #include "ShadowRoot.h"
76 #include "SimplifyMarkupCommand.h"
77 #include "Sound.h"
78 #include "SpellChecker.h"
79 #include "SpellingCorrectionCommand.h"
80 #include "StyleProperties.h"
81 #include "Text.h"
82 #include "TextCheckerClient.h"
83 #include "TextCheckingHelper.h"
84 #include "TextEvent.h"
85 #include "TextIterator.h"
86 #include "TypingCommand.h"
87 #include "UserTypingGestureIndicator.h"
88 #include "VisibleUnits.h"
89 #include "htmlediting.h"
90 #include "markup.h"
91 #include <wtf/unicode/CharacterNames.h>
92 #include <wtf/unicode/Unicode.h>
93
94 #if ENABLE(DELETION_UI)
95 #include "DeleteButtonController.h"
96 #endif
97
98 #if PLATFORM(IOS)
99 #include "DictationCommandIOS.h"
100 #include <wtf/text/StringBuilder.h>
101 #include <wtf/text/WTFString.h>
102 #endif
103
104 namespace WebCore {
105
106 #if PLATFORM(IOS)
107 class ClearTextCommand : public DeleteSelectionCommand {
108 public:
109     ClearTextCommand(Document& document);
110     static void CreateAndApply(const RefPtr<Frame> frame);
111     
112 private:
113     virtual EditAction editingAction() const;
114 };
115
116 ClearTextCommand::ClearTextCommand(Document& document)
117     : DeleteSelectionCommand(document, false, true, false, false, true)
118 {
119 }
120
121 EditAction ClearTextCommand::editingAction() const
122 {
123     return EditActionDelete;
124 }
125
126 void ClearTextCommand::CreateAndApply(const RefPtr<Frame> frame)
127 {
128     if (frame->selection().isNone())
129         return;
130
131     // Don't leave around stale composition state.
132     frame->editor().clear();
133     
134     const VisibleSelection oldSelection = frame->selection().selection();
135     frame->selection().selectAll();
136     RefPtr<ClearTextCommand> clearCommand = adoptRef(new ClearTextCommand(*frame->document()));
137     clearCommand->setStartingSelection(oldSelection);
138     applyCommand(clearCommand.release());
139 }
140 #endif
141
142 using namespace HTMLNames;
143 using namespace WTF;
144 using namespace Unicode;
145
146 #if ENABLE(DELETION_UI)
147
148 PassRefPtr<Range> Editor::avoidIntersectionWithDeleteButtonController(const Range* range) const
149 {
150     if (!range)
151         return 0;
152
153     Node* startContainer = range->startContainer();
154     int startOffset = range->startOffset();
155     Node* endContainer = range->endContainer();
156     int endOffset = range->endOffset();
157
158     if (!startContainer)
159         return 0;
160
161     ASSERT(endContainer);
162
163     Element* element = m_deleteButtonController->containerElement();
164     if (startContainer == element || startContainer->isDescendantOf(element)) {
165         ASSERT(element->parentNode());
166         startContainer = element->parentNode();
167         startOffset = element->nodeIndex();
168     }
169     if (endContainer == element || endContainer->isDescendantOf(element)) {
170         ASSERT(element->parentNode());
171         endContainer = element->parentNode();
172         endOffset = element->nodeIndex();
173     }
174
175     return Range::create(range->ownerDocument(), startContainer, startOffset, endContainer, endOffset);
176 }
177
178 VisibleSelection Editor::avoidIntersectionWithDeleteButtonController(const VisibleSelection& selection) const
179 {
180     if (selection.isNone())
181         return selection;
182
183     Element* element = m_deleteButtonController->containerElement();
184     if (!element)
185         return selection;
186     VisibleSelection updatedSelection = selection;
187
188     Position updatedBase = selection.base();
189     updatePositionForNodeRemoval(updatedBase, element);
190     if (updatedBase != selection.base())
191         updatedSelection.setBase(updatedBase);
192
193     Position updatedExtent = selection.extent();
194     updatePositionForNodeRemoval(updatedExtent, element);
195     if (updatedExtent != selection.extent())
196         updatedSelection.setExtent(updatedExtent);
197
198     return updatedSelection;
199 }
200
201 #endif
202
203 // When an event handler has moved the selection outside of a text control
204 // we should use the target control's selection for this editing operation.
205 VisibleSelection Editor::selectionForCommand(Event* event)
206 {
207     VisibleSelection selection = m_frame.selection().selection();
208     if (!event)
209         return selection;
210     // If the target is a text control, and the current selection is outside of its shadow tree,
211     // then use the saved selection for that text control.
212     HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
213     HTMLTextFormControlElement* textFromControlOfTarget = isHTMLTextFormControlElement(*event->target()->toNode()) ? toHTMLTextFormControlElement(event->target()->toNode()) : nullptr;
214     if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
215         if (RefPtr<Range> range = textFromControlOfTarget->selection())
216             return VisibleSelection(range.get(), DOWNSTREAM, selection.isDirectional());
217     }
218     return selection;
219 }
220
221 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
222 EditingBehavior Editor::behavior() const
223 {
224     return EditingBehavior(m_frame.settings().editingBehaviorType());
225 }
226
227 EditorClient* Editor::client() const
228 {
229     if (Page* page = m_frame.page())
230         return page->editorClient();
231     return 0;
232 }
233
234
235 TextCheckerClient* Editor::textChecker() const
236 {
237     if (EditorClient* owner = client())
238         return owner->textChecker();
239     return 0;
240 }
241
242 void Editor::handleKeyboardEvent(KeyboardEvent* event)
243 {
244     if (EditorClient* c = client())
245         c->handleKeyboardEvent(event);
246 }
247
248 void Editor::handleInputMethodKeydown(KeyboardEvent* event)
249 {
250     if (EditorClient* c = client())
251         c->handleInputMethodKeydown(event);
252 }
253
254 bool Editor::handleTextEvent(TextEvent* event)
255 {
256     // Default event handling for Drag and Drop will be handled by DragController
257     // so we leave the event for it.
258     if (event->isDrop())
259         return false;
260
261     if (event->isPaste()) {
262         if (event->pastingFragment())
263 #if PLATFORM(IOS)
264         {
265             if (client()->performsTwoStepPaste(event->pastingFragment()))
266                 return true;
267 #endif
268             replaceSelectionWithFragment(event->pastingFragment(), false, event->shouldSmartReplace(), event->shouldMatchStyle());
269 #if PLATFORM(IOS)
270         }
271 #endif
272         else 
273             replaceSelectionWithText(event->data(), false, event->shouldSmartReplace());
274         return true;
275     }
276
277     String data = event->data();
278     if (data == "\n") {
279         if (event->isLineBreak())
280             return insertLineBreak();
281         return insertParagraphSeparator();
282     }
283
284     return insertTextWithoutSendingTextEvent(data, false, event);
285 }
286
287 bool Editor::canEdit() const
288 {
289     return m_frame.selection().rootEditableElement();
290 }
291
292 bool Editor::canEditRichly() const
293 {
294     return m_frame.selection().isContentRichlyEditable();
295 }
296
297 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
298 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
299 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
300 // normally selectable to implement copy/paste (like divs, or a document body).
301
302 bool Editor::canDHTMLCut()
303 {
304     return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
305 }
306
307 bool Editor::canDHTMLCopy()
308 {
309     return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
310 }
311
312 bool Editor::canDHTMLPaste()
313 {
314     return !dispatchCPPEvent(eventNames().beforepasteEvent, ClipboardNumb);
315 }
316
317 bool Editor::canCut() const
318 {
319     return canCopy() && canDelete();
320 }
321
322 static HTMLImageElement* imageElementFromImageDocument(Document& document)
323 {
324     if (!document.isImageDocument())
325         return 0;
326     
327     HTMLElement* body = document.body();
328     if (!body)
329         return 0;
330     
331     Node* node = body->firstChild();
332     if (!node)
333         return 0;
334     if (!isHTMLImageElement(node))
335         return 0;
336     return toHTMLImageElement(node);
337 }
338
339 bool Editor::canCopy() const
340 {
341     if (imageElementFromImageDocument(document()))
342         return true;
343     FrameSelection& selection = m_frame.selection();
344     return selection.isRange() && !selection.isInPasswordField();
345 }
346
347 bool Editor::canPaste() const
348 {
349     return canEdit();
350 }
351
352 bool Editor::canDelete() const
353 {
354     FrameSelection& selection = m_frame.selection();
355     return selection.isRange() && selection.rootEditableElement();
356 }
357
358 bool Editor::canDeleteRange(Range* range) const
359 {
360     Node* startContainer = range->startContainer();
361     Node* endContainer = range->endContainer();
362     if (!startContainer || !endContainer)
363         return false;
364     
365     if (!startContainer->hasEditableStyle() || !endContainer->hasEditableStyle())
366         return false;
367
368     if (range->collapsed(IGNORE_EXCEPTION)) {
369         VisiblePosition start(range->startPosition(), DOWNSTREAM);
370         VisiblePosition previous = start.previous();
371         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
372         if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer->rootEditableElement())
373             return false;
374     }
375     return true;
376 }
377
378 bool Editor::smartInsertDeleteEnabled()
379 {   
380     return client() && client()->smartInsertDeleteEnabled();
381 }
382     
383 bool Editor::canSmartCopyOrDelete()
384 {
385     return client() && client()->smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
386 }
387
388 bool Editor::isSelectTrailingWhitespaceEnabled()
389 {
390     return client() && client()->isSelectTrailingWhitespaceEnabled();
391 }
392
393 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
394 {
395     if (!canEdit())
396         return false;
397
398     if (m_frame.selection().isRange()) {
399         if (isTypingAction) {
400             TypingCommand::deleteKeyPressed(document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
401             revealSelectionAfterEditingOperation();
402         } else {
403             if (killRing)
404                 addToKillRing(selectedRange().get(), false);
405             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
406             // Implicitly calls revealSelectionAfterEditingOperation().
407         }
408     } else {
409         TypingCommand::Options options = 0;
410         if (canSmartCopyOrDelete())
411             options |= TypingCommand::SmartDelete;
412         if (killRing)
413             options |= TypingCommand::KillRing;
414         switch (direction) {
415         case DirectionForward:
416         case DirectionRight:
417             TypingCommand::forwardDeleteKeyPressed(document(), options, granularity);
418             break;
419         case DirectionBackward:
420         case DirectionLeft:
421             TypingCommand::deleteKeyPressed(document(), options, granularity);
422             break;
423         }
424         revealSelectionAfterEditingOperation();
425     }
426
427     // FIXME: We should to move this down into deleteKeyPressed.
428     // clear the "start new kill ring sequence" setting, because it was set to true
429     // when the selection was updated by deleting the range
430     if (killRing)
431         setStartNewKillRingSequence(false);
432
433     return true;
434 }
435
436 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
437 {
438     if (m_frame.selection().isNone())
439         return;
440
441     applyCommand(DeleteSelectionCommand::create(document(), smartDelete));
442 }
443
444 #if PLATFORM(IOS)
445 void Editor::clearText()
446 {
447     ClearTextCommand::CreateAndApply(&m_frame);
448 }
449
450 void Editor::insertDictationPhrases(PassOwnPtr<Vector<Vector<String> > > dictationPhrases, RetainPtr<id> metadata)
451 {
452     if (m_frame.selection().isNone())
453         return;
454         
455     if (dictationPhrases->isEmpty())
456         return;
457         
458     applyCommand(DictationCommandIOS::create(document(), dictationPhrases, metadata));
459 }
460
461 void Editor::setDictationPhrasesAsChildOfElement(PassOwnPtr<Vector<Vector<String> > > dictationPhrases, RetainPtr<id> metadata, Element* element)
462 {
463     // Clear the composition.
464     clear();
465     
466     // Clear the Undo stack, since the operations that follow are not Undoable, and will corrupt the stack.  Some day
467     // we could make them Undoable, and let callers clear the Undo stack explicitly if they wish.
468     clearUndoRedoOperations();
469     
470     m_frame.selection().clear();
471     
472     element->removeChildren();
473     
474     if (dictationPhrases->isEmpty()) {
475         client()->respondToChangedContents();
476         return;
477     }
478     
479     ExceptionCode ec;    
480     RefPtr<Range> context = document().createRange();
481     context->selectNodeContents(element, ec);
482     
483     StringBuilder dictationPhrasesBuilder;
484     size_t dictationPhraseCount = dictationPhrases->size();
485     for (size_t i = 0; i < dictationPhraseCount; i++) {
486         const String& firstInterpretation = dictationPhrases->at(i)[0];
487         dictationPhrasesBuilder.append(firstInterpretation);
488     }
489     String serializedDictationPhrases = dictationPhrasesBuilder.toString();
490     
491     element->appendChild(createFragmentFromText(*context.get(), serializedDictationPhrases), ec);
492     
493     // We need a layout in order to add markers below.
494     document().updateLayout();
495     
496     if (!element->firstChild()->isTextNode()) {
497         // Shouldn't happen.
498         ASSERT(element->firstChild()->isTextNode());
499         return;
500     }
501         
502     Text* textNode = static_cast<Text*>(element->firstChild());
503     int previousDictationPhraseStart = 0;
504     for (size_t i = 0; i < dictationPhraseCount; i++) {
505         const Vector<String>& interpretations = dictationPhrases->at(i);
506         int dictationPhraseLength = interpretations[0].length();
507         int dictationPhraseEnd = previousDictationPhraseStart + dictationPhraseLength;
508         if (interpretations.size() > 1) {
509             RefPtr<Range> dictationPhraseRange = Range::create(document(), textNode, previousDictationPhraseStart, textNode, dictationPhraseEnd);
510             document().markers().addDictationPhraseWithAlternativesMarker(dictationPhraseRange.get(), interpretations);
511         }
512         previousDictationPhraseStart = dictationPhraseEnd;
513     }
514     
515     RefPtr<Range> resultRange = Range::create(document(), textNode, 0, textNode, textNode->length());
516     document().markers().addDictationResultMarker(resultRange.get(), metadata);
517     
518     client()->respondToChangedContents();
519 }
520 #endif
521
522 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
523 {
524     Node* target = findEventTargetFromSelection();
525     if (!target)
526         return;
527     target->dispatchEvent(TextEvent::createForPlainTextPaste(document().domWindow(), pastingText, smartReplace), IGNORE_EXCEPTION);
528 }
529
530 void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool smartReplace, bool matchStyle)
531 {
532     Node* target = findEventTargetFromSelection();
533     if (!target)
534         return;
535     target->dispatchEvent(TextEvent::createForFragmentPaste(document().domWindow(), pastingFragment, smartReplace, matchStyle), IGNORE_EXCEPTION);
536 }
537
538 void Editor::pasteAsPlainTextBypassingDHTML()
539 {
540     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
541 }
542
543 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard& pasteboard)
544 {
545     String text = readPlainTextFromPasteboard(pasteboard);
546     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
547         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
548 }
549
550 String Editor::readPlainTextFromPasteboard(Pasteboard& pasteboard)
551 {
552     PasteboardPlainText text;
553     pasteboard.read(text);
554     return plainTextFromPasteboard(text);
555 }
556
557 #if !(PLATFORM(MAC) && !PLATFORM(IOS))
558
559 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
560 {
561     return text.text;
562 }
563
564 #endif
565
566 #if !PLATFORM(MAC) && !PLATFORM(EFL) && !PLATFORM(NIX)
567 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
568 {
569     RefPtr<Range> range = selectedRange();
570     if (!range)
571         return;
572
573     bool chosePlainText;
574     RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, *range, allowPlainText, chosePlainText);
575     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
576         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), chosePlainText);
577 }
578 #endif
579
580 bool Editor::canSmartReplaceWithPasteboard(Pasteboard& pasteboard)
581 {
582     return client() && client()->smartInsertDeleteEnabled() && pasteboard.canSmartReplace();
583 }
584
585 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
586 {
587     if (!client())
588         return false;
589     
590     if (fragment) {
591         Node* child = fragment->firstChild();
592         if (child && fragment->lastChild() == child && child->isCharacterDataNode())
593             return client()->shouldInsertText(toCharacterData(child)->data(), replacingDOMRange.get(), givenAction);
594     }
595
596     return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
597 }
598
599 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
600 {
601     if (m_frame.selection().isNone() || !m_frame.selection().isContentEditable() || !fragment)
602         return;
603
604     ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
605     if (selectReplacement)
606         options |= ReplaceSelectionCommand::SelectReplacement;
607     if (smartReplace)
608         options |= ReplaceSelectionCommand::SmartReplace;
609     if (matchStyle)
610         options |= ReplaceSelectionCommand::MatchStyle;
611     applyCommand(ReplaceSelectionCommand::create(document(), fragment, options, EditActionPaste));
612     revealSelectionAfterEditingOperation();
613
614     if (m_frame.selection().isInPasswordField() || !isContinuousSpellCheckingEnabled())
615         return;
616     Node* nodeToCheck = m_frame.selection().rootEditableElement();
617     if (!nodeToCheck)
618         return;
619
620     RefPtr<Range> rangeToCheck = Range::create(document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
621     m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
622 }
623
624 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
625 {
626     RefPtr<Range> range = selectedRange();
627     if (!range)
628         return;
629
630     replaceSelectionWithFragment(createFragmentFromText(*range, text), selectReplacement, smartReplace, true);
631 }
632
633 PassRefPtr<Range> Editor::selectedRange()
634 {
635     return m_frame.selection().toNormalizedRange();
636 }
637
638 #if PLATFORM(IOS)
639 void Editor::confirmMarkedText()
640 {
641     // FIXME: This is a hacky workaround for the keyboard calling this method too late -
642     // after the selection and focus have already changed.  See <rdar://problem/5975559>
643     Element* focused = document().focusedElement();
644     Node* composition = compositionNode();
645     
646     if (composition && focused && focused != composition && !composition->isDescendantOrShadowDescendantOf(focused)) {
647         cancelComposition();
648         document().setFocusedElement(focused);
649     } else
650         confirmComposition();
651 }
652
653 void Editor::setTextAsChildOfElement(const String& text, Element* elem)
654 {
655     // Clear the composition
656     clear();
657     
658     // Clear the Undo stack, since the operations that follow are not Undoable, and will corrupt the stack.  Some day
659     // we could make them Undoable, and let callers clear the Undo stack explicitly if they wish.
660     clearUndoRedoOperations();
661     
662     // If the element is empty already and we're not adding text, we can early return and avoid clearing/setting
663     // a selection at [0, 0] and the expense involved in creation VisiblePositions.
664     if (!elem->firstChild() && text.isEmpty())
665         return;
666     
667     // As a side effect this function sets a caret selection after the inserted content.  Much of what 
668     // follows is more expensive if there is a selection, so clear it since it's going to change anyway.
669     m_frame.selection().clear();
670     
671     // clear out all current children of element
672     elem->removeChildren();
673
674     if (text.length()) {
675         // insert new text
676         // remove element from tree while doing it
677         // FIXME: The element we're inserting into is often the body element.  It seems strange to be removing it
678         // (even if it is only temporary).  ReplaceSelectionCommand doesn't bother doing this when it inserts
679         // content, why should we here?
680         ExceptionCode ec;
681         RefPtr<Node> parent = elem->parentNode();
682         RefPtr<Node> siblingAfter = elem->nextSibling();
683         if (parent)
684             elem->remove(ec);    
685             
686         RefPtr<Range> context = document().createRange();
687         context->selectNodeContents(elem, ec);
688         RefPtr<DocumentFragment> fragment = createFragmentFromText(*context.get(), text);
689         elem->appendChild(fragment, ec);
690     
691         // restore element to document
692         if (parent) {
693             if (siblingAfter)
694                 parent->insertBefore(elem, siblingAfter.get(), ec);
695             else
696                 parent->appendChild(elem, ec);
697         }
698     }
699
700     // set the selection to the end
701     VisibleSelection selection;
702
703     Position pos = createLegacyEditingPosition(elem, elem->childNodeCount());
704
705     VisiblePosition visiblePos(pos, VP_DEFAULT_AFFINITY);
706     if (visiblePos.isNull())
707         return;
708
709     selection.setBase(visiblePos);
710     selection.setExtent(visiblePos);
711      
712     m_frame.selection().setSelection(selection);
713     
714     client()->respondToChangedContents();
715 }
716 #endif
717
718 bool Editor::shouldDeleteRange(Range* range) const
719 {
720     if (!range || range->collapsed(IGNORE_EXCEPTION))
721         return false;
722     
723     if (!canDeleteRange(range))
724         return false;
725
726     return client() && client()->shouldDeleteRange(range);
727 }
728
729 bool Editor::tryDHTMLCopy()
730 {   
731     if (m_frame.selection().isInPasswordField())
732         return false;
733
734     return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
735 }
736
737 bool Editor::tryDHTMLCut()
738 {
739     if (m_frame.selection().isInPasswordField())
740         return false;
741     
742     return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
743 }
744
745 bool Editor::tryDHTMLPaste()
746 {
747     return !dispatchCPPEvent(eventNames().pasteEvent, ClipboardReadable);
748 }
749
750 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
751 {
752     return client() && client()->shouldInsertText(text, range, action);
753 }
754
755 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
756 {
757 #if PLATFORM(IOS)
758     // FIXME: Merge this to open source https://bugs.webkit.org/show_bug.cgi?id=38830
759     if (m_ignoreCompositionSelectionChange)
760         return;
761 #endif
762
763     if (client())
764         client()->respondToChangedSelection(&m_frame);
765     setStartNewKillRingSequence(true);
766 #if ENABLE(DELETION_UI)
767     m_deleteButtonController->respondToChangedSelection(oldSelection);
768 #endif
769     m_alternativeTextController->respondToChangedSelection(oldSelection, options);
770 }
771
772 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
773 {
774     if (AXObjectCache::accessibilityEnabled()) {
775         Node* node = endingSelection.start().deprecatedNode();
776         if (AXObjectCache* cache = document().existingAXObjectCache())
777             cache->postNotification(node, AXObjectCache::AXValueChanged, TargetObservableParent);
778     }
779
780     updateMarkersForWordsAffectedByEditing(true);
781
782     if (client())
783         client()->respondToChangedContents();
784 }
785
786 bool Editor::hasBidiSelection() const
787 {
788     if (m_frame.selection().isNone())
789         return false;
790
791     Node* startNode;
792     if (m_frame.selection().isRange()) {
793         startNode = m_frame.selection().selection().start().downstream().deprecatedNode();
794         Node* endNode = m_frame.selection().selection().end().upstream().deprecatedNode();
795         if (enclosingBlock(startNode) != enclosingBlock(endNode))
796             return false;
797     } else
798         startNode = m_frame.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
799
800     auto renderer = startNode->renderer();
801     while (renderer && !renderer->isRenderBlockFlow())
802         renderer = renderer->parent();
803
804     if (!renderer)
805         return false;
806
807     if (!renderer->style().isLeftToRightDirection())
808         return true;
809
810     return toRenderBlockFlow(renderer)->containsNonZeroBidiLevel();
811 }
812
813 TriState Editor::selectionUnorderedListState() const
814 {
815     if (m_frame.selection().isCaret()) {
816         if (enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag))
817             return TrueTriState;
818     } else if (m_frame.selection().isRange()) {
819         Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag);
820         Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), ulTag);
821         if (startNode && endNode && startNode == endNode)
822             return TrueTriState;
823     }
824
825     return FalseTriState;
826 }
827
828 TriState Editor::selectionOrderedListState() const
829 {
830     if (m_frame.selection().isCaret()) {
831         if (enclosingNodeWithTag(m_frame.selection().selection().start(), olTag))
832             return TrueTriState;
833     } else if (m_frame.selection().isRange()) {
834         Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), olTag);
835         Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), olTag);
836         if (startNode && endNode && startNode == endNode)
837             return TrueTriState;
838     }
839
840     return FalseTriState;
841 }
842
843 PassRefPtr<Node> Editor::insertOrderedList()
844 {
845     if (!canEditRichly())
846         return 0;
847         
848     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::OrderedList);
849     revealSelectionAfterEditingOperation();
850     return newList;
851 }
852
853 PassRefPtr<Node> Editor::insertUnorderedList()
854 {
855     if (!canEditRichly())
856         return 0;
857         
858     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::UnorderedList);
859     revealSelectionAfterEditingOperation();
860     return newList;
861 }
862
863 bool Editor::canIncreaseSelectionListLevel()
864 {
865     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(&document());
866 }
867
868 bool Editor::canDecreaseSelectionListLevel()
869 {
870     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(&document());
871 }
872
873 PassRefPtr<Node> Editor::increaseSelectionListLevel()
874 {
875     if (!canEditRichly() || m_frame.selection().isNone())
876         return 0;
877     
878     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(&document());
879     revealSelectionAfterEditingOperation();
880     return newList;
881 }
882
883 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
884 {
885     if (!canEditRichly() || m_frame.selection().isNone())
886         return 0;
887     
888     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(&document());
889     revealSelectionAfterEditingOperation();
890     return newList.release();
891 }
892
893 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
894 {
895     if (!canEditRichly() || m_frame.selection().isNone())
896         return 0;
897     
898     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(&document());
899     revealSelectionAfterEditingOperation();
900     return newList.release();
901 }
902
903 void Editor::decreaseSelectionListLevel()
904 {
905     if (!canEditRichly() || m_frame.selection().isNone())
906         return;
907     
908     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(&document());
909     revealSelectionAfterEditingOperation();
910 }
911
912 void Editor::removeFormattingAndStyle()
913 {
914     applyCommand(RemoveFormatCommand::create(document()));
915 }
916
917 void Editor::clearLastEditCommand() 
918 {
919     m_lastEditCommand.clear();
920 }
921 #if PLATFORM(IOS)
922 // If the selection is adjusted from UIKit without closing the typing, the typing command may
923 // have a stale selection.
924 void Editor::ensureLastEditCommandHasCurrentSelectionIfOpenForMoreTyping()
925 {
926     TypingCommand::ensureLastEditCommandHasCurrentSelectionIfOpenForMoreTyping(&m_frame, m_frame.selection().selection());
927 }
928 #endif
929
930 // Returns whether caller should continue with "the default processing", which is the same as 
931 // the event handler NOT setting the return value to false
932 bool Editor::dispatchCPPEvent(const AtomicString& eventType, ClipboardAccessPolicy policy)
933 {
934     Node* target = findEventTargetFromSelection();
935     if (!target)
936         return true;
937
938     RefPtr<Clipboard> clipboard = Clipboard::createForCopyAndPaste(policy);
939
940     RefPtr<Event> event = ClipboardEvent::create(eventType, true, true, clipboard);
941     target->dispatchEvent(event, IGNORE_EXCEPTION);
942     bool noDefaultProcessing = event->defaultPrevented();
943     if (noDefaultProcessing && policy == ClipboardWritable) {
944         OwnPtr<Pasteboard> pasteboard = Pasteboard::createForCopyAndPaste();
945         pasteboard->clear();
946         pasteboard->writePasteboard(clipboard->pasteboard());
947     }
948
949     // invalidate clipboard here for security
950     clipboard->setAccessPolicy(ClipboardNumb);
951     
952     return !noDefaultProcessing;
953 }
954
955 Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
956 {
957     Node* target = selection.start().element();
958     if (!target)
959         target = document().body();
960     if (!target)
961         return 0;
962
963     return target;
964 }
965
966 Node* Editor::findEventTargetFromSelection() const
967 {
968     return findEventTargetFrom(m_frame.selection().selection());
969 }
970
971 void Editor::applyStyle(StyleProperties* style, EditAction editingAction)
972 {
973     switch (m_frame.selection().selectionType()) {
974     case VisibleSelection::NoSelection:
975         // do nothing
976         break;
977     case VisibleSelection::CaretSelection:
978         computeAndSetTypingStyle(style, editingAction);
979         break;
980     case VisibleSelection::RangeSelection:
981         if (style)
982             applyCommand(ApplyStyleCommand::create(document(), EditingStyle::create(style).get(), editingAction));
983         break;
984     }
985 }
986     
987 bool Editor::shouldApplyStyle(StyleProperties* style, Range* range)
988 {   
989     return client()->shouldApplyStyle(style, range);
990 }
991     
992 void Editor::applyParagraphStyle(StyleProperties* style, EditAction editingAction)
993 {
994     switch (m_frame.selection().selectionType()) {
995     case VisibleSelection::NoSelection:
996         // do nothing
997         break;
998     case VisibleSelection::CaretSelection:
999     case VisibleSelection::RangeSelection:
1000         if (style)
1001             applyCommand(ApplyStyleCommand::create(document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties));
1002         break;
1003     }
1004 }
1005
1006 void Editor::applyStyleToSelection(StyleProperties* style, EditAction editingAction)
1007 {
1008     if (!style || style->isEmpty() || !canEditRichly())
1009         return;
1010
1011     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
1012         applyStyle(style, editingAction);
1013 }
1014
1015 void Editor::applyParagraphStyleToSelection(StyleProperties* style, EditAction editingAction)
1016 {
1017     if (!style || style->isEmpty() || !canEditRichly())
1018         return;
1019     
1020     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
1021         applyParagraphStyle(style, editingAction);
1022 }
1023
1024 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
1025 {
1026     return EditingStyle::create(propertyID, value)->triStateOfStyle(
1027         EditingStyle::styleAtSelectionStart(m_frame.selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
1028 }
1029
1030 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
1031 {
1032     return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame.selection().selection());
1033 }
1034
1035 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
1036 {
1037     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(),
1038         propertyID == CSSPropertyBackgroundColor);
1039     if (!selectionStyle || !selectionStyle->style())
1040         return String();
1041
1042     if (propertyID == CSSPropertyFontSize)
1043         return String::number(selectionStyle->legacyFontSize(&document()));
1044     return selectionStyle->style()->getPropertyValue(propertyID);
1045 }
1046
1047 void Editor::indent()
1048 {
1049     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Indent));
1050 }
1051
1052 void Editor::outdent()
1053 {
1054     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Outdent));
1055 }
1056
1057 static void dispatchEditableContentChangedEvents(PassRefPtr<Element> prpStartRoot, PassRefPtr<Element> prpEndRoot)
1058 {
1059     RefPtr<Element> startRoot = prpStartRoot;
1060     RefPtr<Element> endRoot = prpEndRoot;
1061     if (startRoot)
1062         startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
1063     if (endRoot && endRoot != startRoot)
1064         endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
1065 }
1066
1067 void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
1068 {
1069     document().updateLayout();
1070
1071     EditCommandComposition* composition = cmd->composition();
1072     ASSERT(composition);
1073     VisibleSelection newSelection(cmd->endingSelection());
1074
1075     m_alternativeTextController->respondToAppliedEditing(cmd.get());
1076
1077     // Don't clear the typing style with this selection change.  We do those things elsewhere if necessary.
1078     FrameSelection::SetSelectionOptions options = cmd->isDictationCommand() ? FrameSelection::DictationTriggered : 0;
1079     changeSelectionAfterCommand(newSelection, options);
1080     dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
1081
1082     if (!cmd->preservesTypingStyle())
1083         m_frame.selection().clearTypingStyle();
1084
1085     // Command will be equal to last edit command only in the case of typing
1086     if (m_lastEditCommand.get() == cmd)
1087         ASSERT(cmd->isTypingCommand());
1088     else {
1089         // Only register a new undo command if the command passed in is
1090         // different from the last command
1091         m_lastEditCommand = cmd;
1092         if (client())
1093             client()->registerUndoStep(m_lastEditCommand->ensureComposition());
1094     }
1095
1096     respondToChangedContents(newSelection);
1097 }
1098
1099 void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
1100 {
1101     document().updateLayout();
1102
1103     VisibleSelection newSelection(cmd->startingSelection());
1104     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
1105     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
1106
1107     m_alternativeTextController->respondToUnappliedEditing(cmd.get());
1108
1109     m_lastEditCommand = 0;
1110     if (client())
1111         client()->registerRedoStep(cmd);
1112     respondToChangedContents(newSelection);
1113 }
1114
1115 void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
1116 {
1117     document().updateLayout();
1118
1119     VisibleSelection newSelection(cmd->endingSelection());
1120     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
1121     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
1122
1123     m_lastEditCommand = 0;
1124     if (client())
1125         client()->registerUndoStep(cmd);
1126     respondToChangedContents(newSelection);
1127 }
1128
1129 Editor::Editor(Frame& frame)
1130     : m_frame(frame)
1131 #if ENABLE(DELETION_UI)
1132     , m_deleteButtonController(adoptPtr(new DeleteButtonController(frame)))
1133 #endif
1134     , m_ignoreCompositionSelectionChange(false)
1135     , m_shouldStartNewKillRingSequence(false)
1136     // This is off by default, since most editors want this behavior (this matches IE but not FF).
1137     , m_shouldStyleWithCSS(false)
1138     , m_killRing(adoptPtr(new KillRing))
1139     , m_spellChecker(adoptPtr(new SpellChecker(frame)))
1140     , m_alternativeTextController(adoptPtr(new AlternativeTextController(frame)))
1141     , m_areMarkedTextMatchesHighlighted(false)
1142     , m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv)
1143     , m_overwriteModeEnabled(false)
1144 {
1145 }
1146
1147 Editor::~Editor()
1148 {
1149 }
1150
1151 void Editor::clear()
1152 {
1153     m_compositionNode = 0;
1154     m_customCompositionUnderlines.clear();
1155     m_shouldStyleWithCSS = false;
1156     m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
1157
1158 #if ENABLE(DELETION_UI)
1159     m_deleteButtonController = adoptPtr(new DeleteButtonController(m_frame));
1160 #endif
1161 }
1162
1163 bool Editor::insertText(const String& text, Event* triggeringEvent)
1164 {
1165     return m_frame.eventHandler().handleTextInputEvent(text, triggeringEvent);
1166 }
1167
1168 bool Editor::insertTextForConfirmedComposition(const String& text)
1169 {
1170     return m_frame.eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
1171 }
1172
1173 bool Editor::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent)
1174 {
1175     return m_alternativeTextController->insertDictatedText(text, dictationAlternatives, triggeringEvent);
1176 }
1177
1178 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
1179 {
1180     if (text.isEmpty())
1181         return false;
1182
1183     VisibleSelection selection = selectionForCommand(triggeringEvent);
1184     if (!selection.isContentEditable())
1185         return false;
1186     RefPtr<Range> range = selection.toNormalizedRange();
1187
1188     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
1189         return true;
1190
1191     updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
1192
1193     bool shouldConsiderApplyingAutocorrection = false;
1194     if (text == " " || text == "\t")
1195         shouldConsiderApplyingAutocorrection = true;
1196
1197     if (text.length() == 1 && u_ispunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
1198         shouldConsiderApplyingAutocorrection = true;
1199
1200     bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1201
1202     // Get the selection to use for the event that triggered this insertText.
1203     // If the event handler changed the selection, we may want to use a different selection
1204     // that is contained in the event target.
1205     selection = selectionForCommand(triggeringEvent);
1206     if (selection.isContentEditable()) {
1207         if (Node* selectionStart = selection.start().deprecatedNode()) {
1208             Ref<Document> document(selectionStart->document());
1209
1210             // Insert the text
1211             if (triggeringEvent && triggeringEvent->isDictation())
1212                 DictationCommand::insertText(&document.get(), text, triggeringEvent->dictationAlternatives(), selection);
1213             else {
1214                 TypingCommand::Options options = 0;
1215                 if (selectInsertedText)
1216                     options |= TypingCommand::SelectInsertedText;
1217                 if (autocorrectionWasApplied)
1218                     options |= TypingCommand::RetainAutocorrectionIndicator;
1219                 TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
1220             }
1221
1222             // Reveal the current selection
1223             if (Frame* editedFrame = document->frame())
1224                 if (Page* page = editedFrame->page())
1225                     page->focusController().focusedOrMainFrame().selection().revealSelection(ScrollAlignment::alignCenterIfNeeded);
1226         }
1227     }
1228
1229     return true;
1230 }
1231
1232 bool Editor::insertLineBreak()
1233 {
1234     if (!canEdit())
1235         return false;
1236
1237     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1238         return true;
1239
1240     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1241     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1242     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1243     TypingCommand::insertLineBreak(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1244     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1245
1246     return true;
1247 }
1248
1249 bool Editor::insertParagraphSeparator()
1250 {
1251     if (!canEdit())
1252         return false;
1253
1254     if (!canEditRichly())
1255         return insertLineBreak();
1256
1257     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1258         return true;
1259
1260     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1261     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1262     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1263     TypingCommand::insertParagraphSeparator(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1264     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1265
1266     return true;
1267 }
1268
1269 void Editor::cut()
1270 {
1271     if (tryDHTMLCut())
1272         return; // DHTML did the whole operation
1273     if (!canCut()) {
1274         systemBeep();
1275         return;
1276     }
1277
1278     // FIXME: This should share more code with the copy function; there is a lot of overlap.
1279     RefPtr<Range> selection = selectedRange();
1280     willWriteSelectionToPasteboard(selection);
1281     if (shouldDeleteRange(selection.get())) {
1282         updateMarkersForWordsAffectedByEditing(true);
1283         if (enclosingTextFormControl(m_frame.selection().start()))
1284             Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForClipboard(), canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1285         else {
1286 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1287             writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
1288 #else
1289             // FIXME: Convert all other platforms to match Mac and delete this.
1290             Pasteboard::createForCopyAndPaste()->writeSelection(*selection, canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1291 #endif
1292         }
1293         didWriteSelectionToPasteboard();
1294         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1295     }
1296 }
1297
1298 void Editor::copy()
1299 {
1300     if (tryDHTMLCopy())
1301         return; // DHTML did the whole operation
1302     if (!canCopy()) {
1303         systemBeep();
1304         return;
1305     }
1306
1307     willWriteSelectionToPasteboard(selectedRange());
1308     if (enclosingTextFormControl(m_frame.selection().start())) {
1309         Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForClipboard(),
1310             canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1311     } else {
1312         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document())) {
1313 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1314             writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *imageElement, document().url(), document().title());
1315 #else
1316             Pasteboard::createForCopyAndPaste()->writeImage(*imageElement, document().url(), document().title());
1317 #endif
1318         } else {
1319 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1320             writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
1321 #else
1322             // FIXME: Convert all other platforms to match Mac and delete this.
1323             Pasteboard::createForCopyAndPaste()->writeSelection(*selectedRange(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1324 #endif
1325         }
1326     }
1327
1328     didWriteSelectionToPasteboard();
1329 }
1330
1331 void Editor::paste()
1332 {
1333     paste(*Pasteboard::createForCopyAndPaste());
1334 }
1335
1336 void Editor::paste(Pasteboard& pasteboard)
1337 {
1338     if (tryDHTMLPaste())
1339         return; // DHTML did the whole operation
1340     if (!canPaste())
1341         return;
1342     updateMarkersForWordsAffectedByEditing(false);
1343     CachedResourceLoader* loader = document().cachedResourceLoader();
1344     ResourceCacheValidationSuppressor validationSuppressor(loader);
1345     if (m_frame.selection().isContentRichlyEditable())
1346         pasteWithPasteboard(&pasteboard, true);
1347     else
1348         pasteAsPlainTextWithPasteboard(pasteboard);
1349 }
1350
1351 void Editor::pasteAsPlainText()
1352 {
1353     if (tryDHTMLPaste())
1354         return;
1355     if (!canPaste())
1356         return;
1357     updateMarkersForWordsAffectedByEditing(false);
1358     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
1359 }
1360
1361 void Editor::performDelete()
1362 {
1363     if (!canDelete()) {
1364         systemBeep();
1365         return;
1366     }
1367
1368     addToKillRing(selectedRange().get(), false);
1369     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1370
1371     // clear the "start new kill ring sequence" setting, because it was set to true
1372     // when the selection was updated by deleting the range
1373     setStartNewKillRingSequence(false);
1374 }
1375
1376 void Editor::simplifyMarkup(Node* startNode, Node* endNode)
1377 {
1378     if (!startNode)
1379         return;
1380     if (endNode) {
1381         if (&startNode->document() != &endNode->document())
1382             return;
1383         // check if start node is before endNode
1384         Node* node = startNode;
1385         while (node && node != endNode)
1386             node = NodeTraversal::next(node);
1387         if (!node)
1388             return;
1389     }
1390     
1391     applyCommand(SimplifyMarkupCommand::create(document(), startNode, (endNode) ? NodeTraversal::next(endNode) : 0));
1392 }
1393
1394 #if !PLATFORM(IOS)
1395 void Editor::copyURL(const URL& url, const String& title)
1396 {
1397     copyURL(url, title, *Pasteboard::createForCopyAndPaste());
1398 }
1399
1400 void Editor::copyURL(const URL& url, const String& title, Pasteboard& pasteboard)
1401 {
1402     PasteboardURL pasteboardURL;
1403     pasteboardURL.url = url;
1404     pasteboardURL.title = title;
1405
1406 #if PLATFORM(MAC) && !PLATFORM(IOS)
1407     fillInUserVisibleForm(pasteboardURL);
1408 #endif
1409
1410     pasteboard.write(pasteboardURL);
1411 }
1412
1413 void Editor::copyImage(const HitTestResult& result)
1414 {
1415     Element* element = result.innerNonSharedElement();
1416     if (!element)
1417         return;
1418
1419     URL url = result.absoluteLinkURL();
1420     if (url.isEmpty())
1421         url = result.absoluteImageURL();
1422
1423 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1424     writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *element, url, result.altDisplayString());
1425 #else
1426     Pasteboard::createForCopyAndPaste()->writeImage(*element, url, result.altDisplayString());
1427 #endif
1428 }
1429 #endif
1430
1431 bool Editor::isContinuousSpellCheckingEnabled() const
1432 {
1433     return client() && client()->isContinuousSpellCheckingEnabled();
1434 }
1435
1436 void Editor::toggleContinuousSpellChecking()
1437 {
1438     if (client())
1439         client()->toggleContinuousSpellChecking();
1440 }
1441
1442 bool Editor::isGrammarCheckingEnabled()
1443 {
1444     return client() && client()->isGrammarCheckingEnabled();
1445 }
1446
1447 void Editor::toggleGrammarChecking()
1448 {
1449     if (client())
1450         client()->toggleGrammarChecking();
1451 }
1452
1453 int Editor::spellCheckerDocumentTag()
1454 {
1455     return client() ? client()->spellCheckerDocumentTag() : 0;
1456 }
1457
1458 #if USE(APPKIT)
1459
1460 void Editor::uppercaseWord()
1461 {
1462     if (client())
1463         client()->uppercaseWord();
1464 }
1465
1466 void Editor::lowercaseWord()
1467 {
1468     if (client())
1469         client()->lowercaseWord();
1470 }
1471
1472 void Editor::capitalizeWord()
1473 {
1474     if (client())
1475         client()->capitalizeWord();
1476 }
1477     
1478 #endif
1479
1480 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1481
1482 void Editor::showSubstitutionsPanel()
1483 {
1484     if (!client()) {
1485         LOG_ERROR("No NSSpellChecker");
1486         return;
1487     }
1488
1489     if (client()->substitutionsPanelIsShowing()) {
1490         client()->showSubstitutionsPanel(false);
1491         return;
1492     }
1493     client()->showSubstitutionsPanel(true);
1494 }
1495
1496 bool Editor::substitutionsPanelIsShowing()
1497 {
1498     if (!client())
1499         return false;
1500     return client()->substitutionsPanelIsShowing();
1501 }
1502
1503 void Editor::toggleSmartInsertDelete()
1504 {
1505     if (client())
1506         client()->toggleSmartInsertDelete();
1507 }
1508
1509 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1510 {
1511     return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1512 }
1513
1514 void Editor::toggleAutomaticQuoteSubstitution()
1515 {
1516     if (client())
1517         client()->toggleAutomaticQuoteSubstitution();
1518 }
1519
1520 bool Editor::isAutomaticLinkDetectionEnabled()
1521 {
1522     return client() && client()->isAutomaticLinkDetectionEnabled();
1523 }
1524
1525 void Editor::toggleAutomaticLinkDetection()
1526 {
1527     if (client())
1528         client()->toggleAutomaticLinkDetection();
1529 }
1530
1531 bool Editor::isAutomaticDashSubstitutionEnabled()
1532 {
1533     return client() && client()->isAutomaticDashSubstitutionEnabled();
1534 }
1535
1536 void Editor::toggleAutomaticDashSubstitution()
1537 {
1538     if (client())
1539         client()->toggleAutomaticDashSubstitution();
1540 }
1541
1542 bool Editor::isAutomaticTextReplacementEnabled()
1543 {
1544     return client() && client()->isAutomaticTextReplacementEnabled();
1545 }
1546
1547 void Editor::toggleAutomaticTextReplacement()
1548 {
1549     if (client())
1550         client()->toggleAutomaticTextReplacement();
1551 }
1552
1553 bool Editor::isAutomaticSpellingCorrectionEnabled()
1554 {
1555     return m_alternativeTextController->isAutomaticSpellingCorrectionEnabled();
1556 }
1557
1558 void Editor::toggleAutomaticSpellingCorrection()
1559 {
1560     if (client())
1561         client()->toggleAutomaticSpellingCorrection();
1562 }
1563
1564 #endif
1565
1566 bool Editor::shouldEndEditing(Range* range)
1567 {
1568     return client() && client()->shouldEndEditing(range);
1569 }
1570
1571 bool Editor::shouldBeginEditing(Range* range)
1572 {
1573     return client() && client()->shouldBeginEditing(range);
1574 }
1575
1576 void Editor::clearUndoRedoOperations()
1577 {
1578     if (client())
1579         client()->clearUndoRedoOperations();
1580 }
1581
1582 bool Editor::canUndo()
1583 {
1584     return client() && client()->canUndo();
1585 }
1586
1587 void Editor::undo()
1588 {
1589     if (client())
1590         client()->undo();
1591 }
1592
1593 bool Editor::canRedo()
1594 {
1595     return client() && client()->canRedo();
1596 }
1597
1598 void Editor::redo()
1599 {
1600     if (client())
1601         client()->redo();
1602 }
1603
1604 void Editor::didBeginEditing()
1605 {
1606     if (client())
1607         client()->didBeginEditing();
1608 }
1609
1610 void Editor::didEndEditing()
1611 {
1612     if (client())
1613         client()->didEndEditing();
1614 }
1615
1616 void Editor::willWriteSelectionToPasteboard(PassRefPtr<Range> range)
1617 {
1618     if (client())
1619         client()->willWriteSelectionToPasteboard(range.get());
1620 }
1621
1622 void Editor::didWriteSelectionToPasteboard()
1623 {
1624     if (client())
1625         client()->didWriteSelectionToPasteboard();
1626 }
1627
1628 void Editor::toggleBold()
1629 {
1630     command("ToggleBold").execute();
1631 }
1632
1633 void Editor::toggleUnderline()
1634 {
1635     command("ToggleUnderline").execute();
1636 }
1637
1638 void Editor::setBaseWritingDirection(WritingDirection direction)
1639 {
1640 #if PLATFORM(IOS)
1641     if (inSameParagraph(m_frame.selection().selection().visibleStart(), m_frame.selection().selection().visibleEnd()) && 
1642         baseWritingDirectionForSelectionStart() == direction)
1643         return;
1644 #endif
1645         
1646     Element* focusedElement = document().focusedElement();
1647     if (focusedElement && isHTMLTextFormControlElement(*focusedElement)) {
1648         if (direction == NaturalWritingDirection)
1649             return;
1650         toHTMLElement(focusedElement)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
1651         focusedElement->dispatchInputEvent();
1652         document().updateStyleIfNeeded();
1653         return;
1654     }
1655
1656     RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
1657     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1658     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1659 }
1660
1661 WritingDirection Editor::baseWritingDirectionForSelectionStart() const
1662 {
1663     WritingDirection result = LeftToRightWritingDirection;
1664
1665     Position pos = m_frame.selection().selection().visibleStart().deepEquivalent();
1666     Node* node = pos.deprecatedNode();
1667     if (!node)
1668         return result;
1669
1670     auto renderer = node->renderer();
1671     if (!renderer)
1672         return result;
1673
1674     if (!renderer->isRenderBlockFlow()) {
1675         renderer = renderer->containingBlock();
1676         if (!renderer)
1677             return result;
1678     }
1679
1680     switch (renderer->style().direction()) {
1681     case LTR:
1682         return LeftToRightWritingDirection;
1683     case RTL:
1684         return RightToLeftWritingDirection;
1685     }
1686     
1687     return result;
1688 }
1689
1690 void Editor::selectComposition()
1691 {
1692     RefPtr<Range> range = compositionRange();
1693     if (!range)
1694         return;
1695     
1696     // The composition can start inside a composed character sequence, so we have to override checks.
1697     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1698     VisibleSelection selection;
1699     selection.setWithoutValidation(range->startPosition(), range->endPosition());
1700     m_frame.selection().setSelection(selection, 0);
1701 }
1702
1703 void Editor::confirmComposition()
1704 {
1705     if (!m_compositionNode)
1706         return;
1707     setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
1708 }
1709
1710 void Editor::cancelComposition()
1711 {
1712     if (!m_compositionNode)
1713         return;
1714     setComposition(emptyString(), CancelComposition);
1715 }
1716
1717 bool Editor::cancelCompositionIfSelectionIsInvalid()
1718 {
1719     unsigned start;
1720     unsigned end;
1721     if (!hasComposition() || ignoreCompositionSelectionChange() || getCompositionSelection(start, end))
1722         return false;
1723
1724     cancelComposition();
1725     return true;
1726 }
1727
1728 void Editor::confirmComposition(const String& text)
1729 {
1730     setComposition(text, ConfirmComposition);
1731 }
1732
1733 void Editor::setComposition(const String& text, SetCompositionMode mode)
1734 {
1735     ASSERT(mode == ConfirmComposition || mode == CancelComposition);
1736     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1737
1738     setIgnoreCompositionSelectionChange(true);
1739
1740     if (mode == CancelComposition)
1741         ASSERT(text == emptyString());
1742     else
1743         selectComposition();
1744
1745     if (m_frame.selection().isNone()) {
1746         setIgnoreCompositionSelectionChange(false);
1747         return;
1748     }
1749     
1750     // Dispatch a compositionend event to the focused node.
1751     // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
1752     // the DOM Event specification.
1753     if (Element* target = document().focusedElement()) {
1754         RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, document().domWindow(), text);
1755         target->dispatchEvent(event.release(), IGNORE_EXCEPTION);
1756     }
1757
1758     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1759     // will delete the old composition with an optimized replace operation.
1760     if (text.isEmpty() && mode != CancelComposition)
1761         TypingCommand::deleteSelection(document(), 0);
1762
1763     m_compositionNode = 0;
1764     m_customCompositionUnderlines.clear();
1765
1766     insertTextForConfirmedComposition(text);
1767
1768     if (mode == CancelComposition) {
1769         // An open typing command that disagrees about current selection would cause issues with typing later on.
1770         TypingCommand::closeTyping(&m_frame);
1771     }
1772
1773     setIgnoreCompositionSelectionChange(false);
1774 }
1775
1776 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1777 {
1778     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1779
1780     setIgnoreCompositionSelectionChange(true);
1781
1782     // Updates styles before setting selection for composition to prevent
1783     // inserting the previous composition text into text nodes oddly.
1784     // See https://bugs.webkit.org/show_bug.cgi?id=46868
1785     document().updateStyleIfNeeded();
1786
1787     selectComposition();
1788
1789     if (m_frame.selection().isNone()) {
1790         setIgnoreCompositionSelectionChange(false);
1791         return;
1792     }
1793
1794 #if PLATFORM(IOS)
1795     client()->startDelayingAndCoalescingContentChangeNotifications();
1796 #endif
1797
1798     Element* target = document().focusedElement();
1799     if (target) {
1800         // Dispatch an appropriate composition event to the focused node.
1801         // We check the composition status and choose an appropriate composition event since this
1802         // function is used for three purposes:
1803         // 1. Starting a new composition.
1804         //    Send a compositionstart and a compositionupdate event when this function creates
1805         //    a new composition node, i.e.
1806         //    m_compositionNode == 0 && !text.isEmpty().
1807         //    Sending a compositionupdate event at this time ensures that at least one
1808         //    compositionupdate event is dispatched.
1809         // 2. Updating the existing composition node.
1810         //    Send a compositionupdate event when this function updates the existing composition
1811         //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
1812         // 3. Canceling the ongoing composition.
1813         //    Send a compositionend event when function deletes the existing composition node, i.e.
1814         //    m_compositionNode != 0 && test.isEmpty().
1815         RefPtr<CompositionEvent> event;
1816         if (!m_compositionNode) {
1817             // We should send a compositionstart event only when the given text is not empty because this
1818             // function doesn't create a composition node when the text is empty.
1819             if (!text.isEmpty()) {
1820                 target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, document().domWindow(), selectedText()));
1821                 event = CompositionEvent::create(eventNames().compositionupdateEvent, document().domWindow(), text);
1822             }
1823         } else {
1824             if (!text.isEmpty())
1825                 event = CompositionEvent::create(eventNames().compositionupdateEvent, document().domWindow(), text);
1826             else
1827                 event = CompositionEvent::create(eventNames().compositionendEvent, document().domWindow(), text);
1828         }
1829         if (event.get())
1830             target->dispatchEvent(event, IGNORE_EXCEPTION);
1831     }
1832
1833     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1834     // will delete the old composition with an optimized replace operation.
1835     if (text.isEmpty())
1836         TypingCommand::deleteSelection(document(), TypingCommand::PreventSpellChecking);
1837
1838     m_compositionNode = 0;
1839     m_customCompositionUnderlines.clear();
1840
1841     if (!text.isEmpty()) {
1842         TypingCommand::insertText(document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
1843
1844         // Find out what node has the composition now.
1845         Position base = m_frame.selection().base().downstream();
1846         Position extent = m_frame.selection().extent();
1847         Node* baseNode = base.deprecatedNode();
1848         unsigned baseOffset = base.deprecatedEditingOffset();
1849         Node* extentNode = extent.deprecatedNode();
1850         unsigned extentOffset = extent.deprecatedEditingOffset();
1851
1852         if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
1853             m_compositionNode = toText(baseNode);
1854             m_compositionStart = baseOffset;
1855             m_compositionEnd = extentOffset;
1856             m_customCompositionUnderlines = underlines;
1857             size_t numUnderlines = m_customCompositionUnderlines.size();
1858             for (size_t i = 0; i < numUnderlines; ++i) {
1859                 m_customCompositionUnderlines[i].startOffset += baseOffset;
1860                 m_customCompositionUnderlines[i].endOffset += baseOffset;
1861             }
1862             if (baseNode->renderer())
1863                 baseNode->renderer()->repaint();
1864
1865             unsigned start = std::min(baseOffset + selectionStart, extentOffset);
1866             unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
1867             RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
1868             m_frame.selection().setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1869         }
1870     }
1871
1872     setIgnoreCompositionSelectionChange(false);
1873
1874 #if PLATFORM(IOS)        
1875     client()->stopDelayingAndCoalescingContentChangeNotifications();
1876 #endif
1877 }
1878
1879 void Editor::ignoreSpelling()
1880 {
1881     if (!client())
1882         return;
1883         
1884     RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange();
1885     if (selectedRange)
1886         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1887
1888     String text = selectedText();
1889     ASSERT(text.length());
1890     textChecker()->ignoreWordInSpellDocument(text);
1891 }
1892
1893 void Editor::learnSpelling()
1894 {
1895     if (!client())
1896         return;
1897         
1898     // FIXME: On Mac OS X, when use "learn" button on "Spelling and Grammar" panel, we don't call this function. It should remove misspelling markers around the learned word, see <rdar://problem/5396072>.
1899
1900     RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange();
1901     if (selectedRange)
1902         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1903
1904     String text = selectedText();
1905     ASSERT(text.length());
1906     textChecker()->learnWord(text);
1907 }
1908
1909 #if !PLATFORM(IOS)
1910 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1911 {
1912     // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1913     // then we wrap and search from the doc start to (approximately) where we started.
1914     
1915     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
1916     // repeated "check spelling" commands work.
1917     VisibleSelection selection(m_frame.selection().selection());
1918     RefPtr<Range> spellingSearchRange(rangeOfContents(document()));
1919
1920     bool startedWithSelection = false;
1921     if (selection.start().deprecatedNode()) {
1922         startedWithSelection = true;
1923         if (startBeforeSelection) {
1924             VisiblePosition start(selection.visibleStart());
1925             // We match AppKit's rule: Start 1 character before the selection.
1926             VisiblePosition oneBeforeStart = start.previous();
1927             setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1928         } else
1929             setStart(spellingSearchRange.get(), selection.visibleEnd());
1930     }
1931
1932     Position position = spellingSearchRange->startPosition();
1933     if (!isEditablePosition(position)) {
1934         // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1935         // selection is editable.
1936         // This can happen in Mail for a mix of non-editable and editable content (like Stationary), 
1937         // when spell checking the whole document before sending the message.
1938         // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1939
1940         position = firstEditablePositionAfterPositionInRoot(position, document().documentElement()).deepEquivalent();
1941         if (position.isNull())
1942             return;
1943         
1944         Position rangeCompliantPosition = position.parentAnchoredEquivalent();
1945         spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), IGNORE_EXCEPTION);
1946         startedWithSelection = false; // won't need to wrap
1947     }
1948     
1949     // topNode defines the whole range we want to operate on 
1950     Node* topNode = highestEditableRoot(position);
1951     // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
1952     spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), IGNORE_EXCEPTION);
1953
1954     // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1955     // at a word boundary. Going back by one char and then forward by a word does the trick.
1956     if (startedWithSelection) {
1957         VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1958         if (oneBeforeStart.isNotNull())
1959             setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1960         // else we were already at the start of the editable node
1961     }
1962
1963     if (spellingSearchRange->collapsed(IGNORE_EXCEPTION))
1964         return; // nothing to search in
1965     
1966     // Get the spell checker if it is available
1967     if (!client())
1968         return;
1969         
1970     // We go to the end of our first range instead of the start of it, just to be sure
1971     // we don't get foiled by any word boundary problems at the start.  It means we might
1972     // do a tiny bit more searching.
1973     Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer();
1974     int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();
1975     
1976     int misspellingOffset = 0;
1977     GrammarDetail grammarDetail;
1978     int grammarPhraseOffset = 0;
1979     RefPtr<Range> grammarSearchRange;
1980     String badGrammarPhrase;
1981     String misspelledWord;
1982
1983     bool isSpelling = true;
1984     int foundOffset = 0;
1985     String foundItem;
1986     RefPtr<Range> firstMisspellingRange;
1987     if (unifiedTextCheckerEnabled()) {
1988         grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
1989         foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1990         if (isSpelling) {
1991             misspelledWord = foundItem;
1992             misspellingOffset = foundOffset;
1993         } else {
1994             badGrammarPhrase = foundItem;
1995             grammarPhraseOffset = foundOffset;
1996         }
1997     } else {
1998         misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1999
2000 #if USE(GRAMMAR_CHECKING)
2001         grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
2002         if (!misspelledWord.isEmpty()) {
2003             // Stop looking at start of next misspelled word
2004             CharacterIterator chars(grammarSearchRange.get());
2005             chars.advance(misspellingOffset);
2006             grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
2007         }
2008     
2009         if (isGrammarCheckingEnabled())
2010             badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
2011 #endif
2012     }
2013     
2014     // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
2015     // block rather than at a selection).
2016     if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
2017         spellingSearchRange->setStart(topNode, 0, IGNORE_EXCEPTION);
2018         // going until the end of the very first chunk we tested is far enough
2019         spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, IGNORE_EXCEPTION);
2020         
2021         if (unifiedTextCheckerEnabled()) {
2022             grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
2023             foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
2024             if (isSpelling) {
2025                 misspelledWord = foundItem;
2026                 misspellingOffset = foundOffset;
2027             } else {
2028                 badGrammarPhrase = foundItem;
2029                 grammarPhraseOffset = foundOffset;
2030             }
2031         } else {
2032             misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
2033
2034 #if USE(GRAMMAR_CHECKING)
2035             grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
2036             if (!misspelledWord.isEmpty()) {
2037                 // Stop looking at start of next misspelled word
2038                 CharacterIterator chars(grammarSearchRange.get());
2039                 chars.advance(misspellingOffset);
2040                 grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
2041             }
2042
2043             if (isGrammarCheckingEnabled())
2044                 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
2045 #endif
2046         }
2047     }
2048     
2049 #if !USE(GRAMMAR_CHECKING)
2050     ASSERT(badGrammarPhrase.isEmpty());
2051     UNUSED_PARAM(grammarPhraseOffset);
2052 #else
2053     if (!badGrammarPhrase.isEmpty()) {
2054         // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
2055         // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
2056         // panel, and store a marker so we draw the green squiggle later.
2057         
2058         ASSERT(badGrammarPhrase.length() > 0);
2059         ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
2060         
2061         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
2062         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
2063         m_frame.selection().setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
2064         m_frame.selection().revealSelection();
2065         
2066         client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
2067         document().markers().addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
2068     } else
2069 #endif
2070     if (!misspelledWord.isEmpty()) {
2071         // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
2072         // a marker so we draw the red squiggle later.
2073         
2074         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
2075         m_frame.selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
2076         m_frame.selection().revealSelection();
2077         
2078         client()->updateSpellingUIWithMisspelledWord(misspelledWord);
2079         document().markers().addMarker(misspellingRange.get(), DocumentMarker::Spelling);
2080     }
2081 }
2082 #endif // !PLATFORM(IOS)
2083
2084 String Editor::misspelledWordAtCaretOrRange(Node* clickedNode) const
2085 {
2086     if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
2087         return String();
2088
2089     VisibleSelection selection = m_frame.selection().selection();
2090     if (!selection.isContentEditable() || selection.isNone())
2091         return String();
2092
2093     VisibleSelection wordSelection(selection.base());
2094     wordSelection.expandUsingGranularity(WordGranularity);
2095     RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
2096
2097     // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
2098     // selection exactly match the word selection.
2099     if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
2100         return String();
2101
2102     String word = wordRange->text();
2103     if (word.isEmpty() || !client())
2104         return String();
2105
2106     int wordLength = word.length();
2107     int misspellingLocation = -1;
2108     int misspellingLength = 0;
2109     textChecker()->checkSpellingOfString(word.characters(), wordLength, &misspellingLocation, &misspellingLength);
2110
2111     return misspellingLength == wordLength ? word : String();
2112 }
2113
2114 String Editor::misspelledSelectionString() const
2115 {
2116     String selectedString = selectedText();
2117     int length = selectedString.length();
2118     if (!length || !client())
2119         return String();
2120
2121     int misspellingLocation = -1;
2122     int misspellingLength = 0;
2123     textChecker()->checkSpellingOfString(selectedString.characters(), length, &misspellingLocation, &misspellingLength);
2124     
2125     // The selection only counts as misspelled if the selected text is exactly one misspelled word
2126     if (misspellingLength != length)
2127         return String();
2128     
2129     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
2130     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
2131     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
2132     // or a grammar error.
2133     client()->updateSpellingUIWithMisspelledWord(selectedString);
2134     
2135     return selectedString;
2136 }
2137
2138 bool Editor::isSelectionUngrammatical()
2139 {
2140 #if USE(GRAMMAR_CHECKING)
2141     RefPtr<Range> range = m_frame.selection().toNormalizedRange();
2142     if (!range)
2143         return false;
2144     return TextCheckingHelper(client(), range).isUngrammatical();
2145 #else
2146     return false;
2147 #endif
2148 }
2149
2150 Vector<String> Editor::guessesForMisspelledWord(const String& word) const
2151 {
2152     ASSERT(word.length());
2153
2154     Vector<String> guesses;
2155     if (client())
2156         textChecker()->getGuessesForWord(word, String(), guesses);
2157     return guesses;
2158 }
2159
2160 Vector<String> Editor::guessesForMisspelledOrUngrammatical(bool& misspelled, bool& ungrammatical)
2161 {
2162     if (unifiedTextCheckerEnabled()) {
2163         RefPtr<Range> range;
2164         FrameSelection& frameSelection = m_frame.selection();
2165         if (frameSelection.isCaret() && behavior().shouldAllowSpellingSuggestionsWithoutSelection()) {
2166             VisibleSelection wordSelection = VisibleSelection(frameSelection.base());
2167             wordSelection.expandUsingGranularity(WordGranularity);
2168             range = wordSelection.toNormalizedRange();
2169         } else
2170             range = frameSelection.toNormalizedRange();
2171         if (!range)
2172             return Vector<String>();
2173         return TextCheckingHelper(client(), range).guessesForMisspelledOrUngrammaticalRange(isGrammarCheckingEnabled(), misspelled, ungrammatical);
2174     }
2175
2176     String misspelledWord = behavior().shouldAllowSpellingSuggestionsWithoutSelection() ? misspelledWordAtCaretOrRange(document().focusedElement()) : misspelledSelectionString();
2177     misspelled = !misspelledWord.isEmpty();
2178     // Only unified text checker supports guesses for ungrammatical phrases.
2179     ungrammatical = false;
2180
2181     if (misspelled)
2182         return guessesForMisspelledWord(misspelledWord);
2183     return Vector<String>();
2184 }
2185
2186 void Editor::showSpellingGuessPanel()
2187 {
2188     if (!client()) {
2189         LOG_ERROR("No NSSpellChecker");
2190         return;
2191     }
2192
2193     if (client()->spellingUIIsShowing()) {
2194         client()->showSpellingUI(false);
2195         return;
2196     }
2197
2198 #if !PLATFORM(IOS)
2199     advanceToNextMisspelling(true);
2200 #endif
2201     client()->showSpellingUI(true);
2202 }
2203
2204 bool Editor::spellingPanelIsShowing()
2205 {
2206     if (!client())
2207         return false;
2208     return client()->spellingUIIsShowing();
2209 }
2210
2211 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
2212 {
2213     RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
2214     if (selectedRange) {
2215         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
2216         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Grammar);
2217     }
2218 }
2219
2220 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
2221 {
2222     markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
2223 }
2224
2225 void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
2226 {
2227 #if PLATFORM(IOS)
2228     UNUSED_PARAM(selectionAfterTyping);
2229     UNUSED_PARAM(doReplacement);
2230     TextCheckingTypeMask textCheckingOptions = 0;
2231     if (isContinuousSpellCheckingEnabled())
2232         textCheckingOptions |= TextCheckingTypeSpelling;
2233     if (!(textCheckingOptions & TextCheckingTypeSpelling))
2234         return;
2235
2236     VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
2237     markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
2238 #else
2239 #if !USE(AUTOMATIC_TEXT_REPLACEMENT)
2240     UNUSED_PARAM(doReplacement);
2241 #endif
2242
2243     if (unifiedTextCheckerEnabled()) {
2244         m_alternativeTextController->applyPendingCorrection(selectionAfterTyping);
2245
2246         TextCheckingTypeMask textCheckingOptions = 0;
2247
2248         if (isContinuousSpellCheckingEnabled())
2249             textCheckingOptions |= TextCheckingTypeSpelling;
2250
2251 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2252         if (doReplacement
2253             && (isAutomaticQuoteSubstitutionEnabled()
2254                 || isAutomaticLinkDetectionEnabled()
2255                 || isAutomaticDashSubstitutionEnabled()
2256                 || isAutomaticTextReplacementEnabled()
2257                 || ((textCheckingOptions & TextCheckingTypeSpelling) && isAutomaticSpellingCorrectionEnabled())))
2258             textCheckingOptions |= TextCheckingTypeReplacement;
2259 #endif
2260         if (!(textCheckingOptions & (TextCheckingTypeSpelling | TextCheckingTypeReplacement)))
2261             return;
2262
2263         if (isGrammarCheckingEnabled())
2264             textCheckingOptions |= TextCheckingTypeGrammar;
2265
2266         VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
2267         if (textCheckingOptions & TextCheckingTypeGrammar) {
2268             VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
2269             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
2270         } else
2271             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
2272         return;
2273     }
2274
2275     if (!isContinuousSpellCheckingEnabled())
2276         return;
2277
2278     // Check spelling of one word
2279     RefPtr<Range> misspellingRange;
2280     markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
2281
2282     // Autocorrect the misspelled word.
2283     if (!misspellingRange)
2284         return;
2285     
2286     // Get the misspelled word.
2287     const String misspelledWord = plainText(misspellingRange.get());
2288     String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
2289
2290     // If autocorrected word is non empty, replace the misspelled word by this word.
2291     if (!autocorrectedString.isEmpty()) {
2292         VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
2293         if (newSelection != m_frame.selection().selection()) {
2294             if (!m_frame.selection().shouldChangeSelection(newSelection))
2295                 return;
2296             m_frame.selection().setSelection(newSelection);
2297         }
2298
2299         if (!m_frame.editor().shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
2300             return;
2301         m_frame.editor().replaceSelectionWithText(autocorrectedString, false, false);
2302
2303         // Reset the charet one character further.
2304         m_frame.selection().moveTo(m_frame.selection().end());
2305         m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2306     }
2307
2308     if (!isGrammarCheckingEnabled())
2309         return;
2310     
2311     // Check grammar of entire sentence
2312     markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
2313 #endif
2314 }
2315     
2316 void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
2317 {
2318 #if !PLATFORM(IOS)
2319     // This function is called with a selection already expanded to word boundaries.
2320     // Might be nice to assert that here.
2321     
2322     // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
2323     // grammar checking can only be on if spell checking is also on.
2324     if (!isContinuousSpellCheckingEnabled())
2325         return;
2326     
2327     RefPtr<Range> searchRange(selection.toNormalizedRange());
2328     if (!searchRange)
2329         return;
2330     
2331     // If we're not in an editable node, bail.
2332     Node* editableNode = searchRange->startContainer();
2333     if (!editableNode || !editableNode->hasEditableStyle())
2334         return;
2335
2336     if (!isSpellCheckingEnabledFor(editableNode))
2337         return;
2338
2339     // Get the spell checker if it is available
2340     if (!client())
2341         return;
2342     
2343     TextCheckingHelper checker(client(), searchRange);
2344     if (checkSpelling)
2345         checker.markAllMisspellings(firstMisspellingRange);
2346     else {
2347 #if USE(GRAMMAR_CHECKING)
2348         if (isGrammarCheckingEnabled())
2349             checker.markAllBadGrammar();
2350 #else
2351         ASSERT_NOT_REACHED();
2352 #endif
2353     }    
2354 #else
2355         UNUSED_PARAM(selection);
2356         UNUSED_PARAM(checkSpelling);
2357         UNUSED_PARAM(firstMisspellingRange);
2358 #endif // !PLATFORM(IOS)
2359 }
2360
2361 bool Editor::isSpellCheckingEnabledFor(Node* node) const
2362 {
2363     if (!node)
2364         return false;
2365     const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
2366     if (!focusedElement)
2367         return false;
2368     return focusedElement->isSpellCheckingEnabled();
2369 }
2370
2371 bool Editor::isSpellCheckingEnabledInFocusedNode() const
2372 {
2373     return isSpellCheckingEnabledFor(m_frame.selection().start().deprecatedNode());
2374 }
2375
2376 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
2377 {
2378     markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
2379 }
2380     
2381 void Editor::markBadGrammar(const VisibleSelection& selection)
2382 {
2383 #if USE(GRAMMAR_CHECKING)
2384     RefPtr<Range> firstMisspellingRange;
2385     markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
2386 #else
2387     ASSERT_NOT_REACHED();
2388 #endif
2389 }
2390
2391 void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
2392 {
2393     ASSERT(unifiedTextCheckerEnabled());
2394
2395     // There shouldn't be pending autocorrection at this moment.
2396     ASSERT(!m_alternativeTextController->hasPendingCorrection());
2397
2398     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2399     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2400
2401     // This function is called with selections already expanded to word boundaries.
2402     if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
2403         return;
2404
2405     // If we're not in an editable node, bail.
2406     Node* editableNode = spellingRange->startContainer();
2407     if (!editableNode || !editableNode->hasEditableStyle())
2408         return;
2409
2410     if (!isSpellCheckingEnabledFor(editableNode))
2411         return;
2412
2413     Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
2414     TextCheckingParagraph paragraphToCheck(rangeToCheck);
2415     if (paragraphToCheck.isRangeEmpty() || paragraphToCheck.isEmpty())
2416         return;
2417     RefPtr<Range> paragraphRange = paragraphToCheck.paragraphRange();
2418
2419     bool asynchronous = m_frame.settings().asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
2420
2421     // In asynchronous mode, we intentionally check paragraph-wide sentence.
2422     RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessIncremental, asynchronous ? paragraphRange : rangeToCheck, paragraphRange);
2423
2424     if (asynchronous) {
2425         m_spellChecker->requestCheckingFor(request);
2426         return;
2427     }
2428
2429     Vector<TextCheckingResult> results;
2430     checkTextOfParagraph(textChecker(), paragraphToCheck.textCharacters(), paragraphToCheck.textLength(),
2431         resolveTextCheckingTypeMask(textCheckingOptions), results);
2432     markAndReplaceFor(request, results);
2433 }
2434
2435 static bool isAutomaticTextReplacementType(TextCheckingType type)
2436 {
2437     switch (type) {
2438     case TextCheckingTypeNone:
2439     case TextCheckingTypeSpelling:
2440     case TextCheckingTypeGrammar:
2441         return false;
2442     case TextCheckingTypeLink:
2443     case TextCheckingTypeQuote:
2444     case TextCheckingTypeDash:
2445     case TextCheckingTypeReplacement:
2446     case TextCheckingTypeCorrection:
2447     case TextCheckingTypeShowCorrectionPanel:
2448         return true;
2449     }
2450     ASSERT_NOT_REACHED();
2451     return false;
2452 }
2453
2454 static void correctSpellcheckingPreservingTextCheckingParagraph(TextCheckingParagraph& paragraph, PassRefPtr<Range> rangeToReplace, const String& replacement, int resultLocation, int resultLength)
2455 {
2456     ContainerNode* scope = toContainerNode(highestAncestor(paragraph.paragraphRange()->startContainer()));
2457
2458     size_t paragraphLocation;
2459     size_t paragraphLength;
2460     TextIterator::getLocationAndLengthFromRange(scope, paragraph.paragraphRange().get(), paragraphLocation, paragraphLength);
2461
2462     applyCommand(SpellingCorrectionCommand::create(rangeToReplace, replacement));
2463
2464     // TextCheckingParagraph may be orphaned after SpellingCorrectionCommand mutated DOM.
2465     // See <rdar://10305315>, http://webkit.org/b/89526.
2466
2467     RefPtr<Range> newParagraphRange = TextIterator::rangeFromLocationAndLength(scope, paragraphLocation, paragraphLength + replacement.length() - resultLength);
2468
2469     paragraph = TextCheckingParagraph(TextIterator::subrange(newParagraphRange.get(), resultLocation, replacement.length()), newParagraphRange);
2470 }
2471
2472 void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
2473 {
2474     ASSERT(request);
2475
2476     TextCheckingTypeMask textCheckingOptions = request->data().mask();
2477     TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
2478
2479     const bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
2480     const bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2481     const bool shouldMarkLink = textCheckingOptions & TextCheckingTypeLink;
2482     const bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
2483     const bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2484     const bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
2485 #if !USE(AUTOCORRECTION_PANEL)
2486     ASSERT(!shouldShowCorrectionPanel);
2487 #endif
2488
2489     // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2490     int selectionOffset = 0;
2491     bool useAmbiguousBoundaryOffset = false;
2492     bool selectionChanged = false;
2493     bool restoreSelectionAfterChange = false;
2494     bool adjustSelectionForParagraphBoundaries = false;
2495
2496     if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2497         if (m_frame.selection().selectionType() == VisibleSelection::CaretSelection) {
2498             // Attempt to save the caret position so we can restore it later if needed
2499             Position caretPosition = m_frame.selection().end();
2500             selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
2501             restoreSelectionAfterChange = true;
2502             if (selectionOffset > 0 && (selectionOffset > paragraph.textLength() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2503                 adjustSelectionForParagraphBoundaries = true;
2504             if (selectionOffset > 0 && selectionOffset <= paragraph.textLength() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
2505                 useAmbiguousBoundaryOffset = true;
2506         }
2507     }
2508
2509     int offsetDueToReplacement = 0;
2510
2511     for (unsigned i = 0; i < results.size(); i++) {
2512         const int spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
2513         const TextCheckingType resultType = results[i].type;
2514         const int resultLocation = results[i].location + offsetDueToReplacement;
2515         const int resultLength = results[i].length;
2516         const int resultEndLocation = resultLocation + resultLength;
2517         const String& replacement = results[i].replacement;
2518         const bool resultEndsAtAmbiguousBoundary = useAmbiguousBoundaryOffset && resultEndLocation == selectionOffset - 1;
2519
2520         // Only mark misspelling if:
2521         // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2522         // 2. Result falls within spellingRange.
2523         // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2524         //    "wouldn'" as misspelled right after apostrophe is typed.
2525         if (shouldMarkSpelling && !shouldShowCorrectionPanel && resultType == TextCheckingTypeSpelling
2526             && resultLocation >= paragraph.checkingStart() && resultEndLocation <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2527             ASSERT(resultLength > 0 && resultLocation >= 0);
2528             RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
2529             if (!m_alternativeTextController->isSpellingMarkerAllowed(misspellingRange))
2530                 continue;
2531             misspellingRange->startContainer()->document().markers().addMarker(misspellingRange.get(), DocumentMarker::Spelling, replacement);
2532         } else if (shouldMarkGrammar && resultType == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
2533             ASSERT(resultLength > 0 && resultLocation >= 0);
2534             const Vector<GrammarDetail>& details = results[i].details;
2535             for (unsigned j = 0; j < details.size(); j++) {
2536                 const GrammarDetail& detail = details[j];
2537                 ASSERT(detail.length > 0 && detail.location >= 0);
2538                 if (paragraph.checkingRangeCovers(resultLocation + detail.location, detail.length)) {
2539                     RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail.location, detail.length);
2540                     badGrammarRange->startContainer()->document().markers().addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail.userDescription);
2541                 }
2542             }
2543         } else if (resultEndLocation <= spellingRangeEndOffset && resultEndLocation >= paragraph.checkingStart()
2544             && isAutomaticTextReplacementType(resultType)) {
2545             // In this case the result range just has to touch the spelling range, so we can handle replacing non-word text such as punctuation.
2546             ASSERT(resultLength > 0 && resultLocation >= 0);
2547
2548             if (shouldShowCorrectionPanel && (resultEndLocation < spellingRangeEndOffset
2549                 || !(resultType & (TextCheckingTypeReplacement | TextCheckingTypeCorrection))))
2550                 continue;
2551
2552             // Apply replacement if:
2553             // 1. The replacement length is non-zero.
2554             // 2. The result doesn't end at an ambiguous boundary.
2555             //    (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2556             bool doReplacement = replacement.length() > 0 && !resultEndsAtAmbiguousBoundary;
2557             RefPtr<Range> rangeToReplace = paragraph.subrange(resultLocation, resultLength);
2558
2559             // adding links should be done only immediately after they are typed
2560             if (resultType == TextCheckingTypeLink && selectionOffset != resultEndLocation + 1)
2561                 continue;
2562
2563             if (!(shouldPerformReplacement || shouldCheckForCorrection || shouldMarkLink) || !doReplacement)
2564                 continue;
2565
2566             String replacedString = plainText(rangeToReplace.get());
2567             const bool existingMarkersPermitReplacement = m_alternativeTextController->processMarkersOnTextToBeReplacedByResult(&results[i], rangeToReplace.get(), replacedString);
2568             if (!existingMarkersPermitReplacement)
2569                 continue;
2570
2571             if (shouldShowCorrectionPanel) {
2572                 if (resultEndLocation == spellingRangeEndOffset) {
2573                     // We only show the correction panel on the last word.
2574                     m_alternativeTextController->show(rangeToReplace, replacement);
2575                     break;
2576                 }
2577                 // If this function is called for showing correction panel, we ignore other correction or replacement.
2578                 continue;
2579             }
2580
2581             VisibleSelection selectionToReplace(rangeToReplace.get(), DOWNSTREAM);
2582             if (selectionToReplace != m_frame.selection().selection()) {
2583                 if (!m_frame.selection().shouldChangeSelection(selectionToReplace))
2584                     continue;
2585             }
2586
2587             if (resultType == TextCheckingTypeLink) {
2588                 m_frame.selection().setSelection(selectionToReplace);
2589                 selectionChanged = true;
2590                 restoreSelectionAfterChange = false;
2591                 if (canEditRichly())
2592                     applyCommand(CreateLinkCommand::create(document(), replacement));
2593             } else if (canEdit() && shouldInsertText(replacement, rangeToReplace.get(), EditorInsertActionTyped)) {
2594                 correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, resultLocation, resultLength);
2595
2596                 if (AXObjectCache* cache = document().existingAXObjectCache()) {
2597                     if (Element* root = m_frame.selection().selection().rootEditableElement())
2598                         cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured);
2599                 }
2600
2601                 // Skip all other results for the replaced text.
2602                 while (i + 1 < results.size() && results[i + 1].location + offsetDueToReplacement <= resultLocation)
2603                     i++;
2604
2605                 selectionChanged = true;
2606                 offsetDueToReplacement += replacement.length() - resultLength;
2607                 if (resultLocation < selectionOffset)
2608                     selectionOffset += replacement.length() - resultLength;
2609
2610                 // Add a marker so that corrections can easily be undone and won't be re-corrected.
2611                 if (resultType == TextCheckingTypeCorrection)
2612                     m_alternativeTextController->markCorrection(paragraph.subrange(resultLocation, replacement.length()), replacedString);
2613             }
2614         }
2615     }
2616
2617     if (selectionChanged) {
2618         TextCheckingParagraph extendedParagraph(paragraph);
2619         // Restore the caret position if we have made any replacements
2620         extendedParagraph.expandRangeToNextEnd();
2621         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2622             RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
2623             m_frame.selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
2624             if (adjustSelectionForParagraphBoundaries)
2625                 m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2626         } else {
2627             // If this fails for any reason, the fallback is to go one position beyond the last replacement
2628             m_frame.selection().moveTo(m_frame.selection().end());
2629             m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2630         }
2631     }
2632 }
2633
2634 void Editor::changeBackToReplacedString(const String& replacedString)
2635 {
2636 #if !PLATFORM(IOS)
2637     ASSERT(unifiedTextCheckerEnabled());
2638
2639     if (replacedString.isEmpty())
2640         return;
2641
2642     RefPtr<Range> selection = selectedRange();
2643     if (!shouldInsertText(replacedString, selection.get(), EditorInsertActionPasted))
2644         return;
2645     
2646     m_alternativeTextController->recordAutocorrectionResponseReversed(replacedString, selection);
2647     TextCheckingParagraph paragraph(selection);
2648     replaceSelectionWithText(replacedString, false, false);
2649     RefPtr<Range> changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2650     changedRange->startContainer()->document().markers().addMarker(changedRange.get(), DocumentMarker::Replacement, String());
2651     m_alternativeTextController->markReversed(changedRange.get());
2652 #else
2653     ASSERT_NOT_REACHED();
2654     UNUSED_PARAM(replacedString);
2655 #endif // !PLATFORM(IOS)
2656 }
2657
2658
2659 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2660 {
2661     if (unifiedTextCheckerEnabled()) {
2662         if (!isContinuousSpellCheckingEnabled())
2663             return;
2664
2665         // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
2666         TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling;
2667         if (markGrammar && isGrammarCheckingEnabled())
2668             textCheckingOptions |= TextCheckingTypeGrammar;
2669         markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
2670         return;
2671     }
2672
2673     RefPtr<Range> firstMisspellingRange;
2674     markMisspellings(spellingSelection, firstMisspellingRange);
2675     if (markGrammar)
2676         markBadGrammar(grammarSelection);
2677 }
2678
2679 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2680 {
2681     m_alternativeTextController->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2682 }
2683
2684 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2685 {
2686     if (!document().markers().hasMarkers())
2687         return;
2688
2689     if (!m_alternativeTextController->shouldRemoveMarkersUponEditing() && (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)))
2690         return;
2691
2692     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2693     // several scenarios:
2694     // 1. Insert in the middle of a word.
2695     // 2. Appending non whitespace at the beginning of word.
2696     // 3. Appending non whitespace at the end of word.
2697     // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2698     // remove the markers on that word.
2699     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2700     // selection, and remove words between the selection boundaries.
2701     //
2702     VisiblePosition startOfSelection = m_frame.selection().selection().start();
2703     VisiblePosition endOfSelection = m_frame.selection().selection().end();
2704     if (startOfSelection.isNull())
2705         return;
2706     // First word is the word that ends after or on the start of selection.
2707     VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2708     VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2709     // Last word is the word that begins before or on the end of selection
2710     VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2711     VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2712
2713     if (startOfFirstWord.isNull()) {
2714         startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2715         endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2716     }
2717     
2718     if (endOfLastWord.isNull()) {
2719         startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2720         endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2721     }
2722
2723     // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2724     // we choose next word as the first word.
2725     if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2726         startOfFirstWord = nextWordPosition(startOfFirstWord);
2727         endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2728         if (startOfFirstWord == endOfSelection)
2729             return;
2730     }
2731
2732     // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2733     // we choose previous word as the last word.
2734     if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2735         startOfLastWord = previousWordPosition(startOfLastWord);
2736         endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2737         if (endOfLastWord == startOfSelection)
2738             return;
2739     }
2740
2741     if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2742         return;
2743
2744     // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2745     // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2746     // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2747     // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2748     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2749     // of marker that contains the word in question, and remove marker on that whole range.
2750     RefPtr<Range> wordRange = Range::create(document(), startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2751
2752     Vector<DocumentMarker*> markers = document().markers().markersInRange(wordRange.get(), DocumentMarker::DictationAlternatives);
2753     for (size_t i = 0; i < markers.size(); ++i)
2754         m_alternativeTextController->removeDictationAlternativesForMarker(markers[i]);
2755
2756 #if PLATFORM(IOS)
2757     document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption | DocumentMarker::DictationAlternatives | DocumentMarker::DictationPhraseWithAlternatives, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2758 #else
2759     document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption | DocumentMarker::DictationAlternatives, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2760 #endif
2761     document().markers().clearDescriptionOnMarkersIntersectingRange(wordRange.get(), DocumentMarker::Replacement);
2762 }
2763
2764 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2765 {
2766     m_alternativeTextController->deletedAutocorrectionAtPosition(position, originalString);
2767 }
2768
2769 PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
2770 {
2771     Document* document = m_frame.documentAtPoint(windowPoint);
2772     if (!document)
2773         return 0;
2774     
2775     Frame* frame = document->frame();
2776     ASSERT(frame);
2777     FrameView* frameView = frame->view();
2778     if (!frameView)
2779         return 0;
2780     IntPoint framePoint = frameView->windowToContents(windowPoint);
2781     VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2782
2783     return avoidIntersectionWithDeleteButtonController(selection.toNormalizedRange().get());
2784 }
2785
2786 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
2787 {
2788     if (m_ignoreCompositionSelectionChange)
2789         return;
2790
2791     m_frame.selection().revealSelection(alignment, revealExtentOption);
2792 }
2793
2794 void Editor::setIgnoreCompositionSelectionChange(bool ignore)
2795 {
2796     if (m_ignoreCompositionSelectionChange == ignore)
2797         return;
2798
2799     m_ignoreCompositionSelectionChange = ignore;
2800 #if PLATFORM(IOS)
2801     // FIXME: Merge this to open source https://bugs.webkit.org/show_bug.cgi?id=38830
2802     if (!ignore)
2803         notifyComponentsOnChangedSelection(m_frame.selection().selection(), 0);
2804 #endif
2805     if (!ignore)
2806         revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
2807 }
2808
2809 PassRefPtr<Range> Editor::compositionRange() const
2810 {
2811     if (!m_compositionNode)
2812         return 0;
2813     unsigned length = m_compositionNode->length();
2814     unsigned start = std::min(m_compositionStart, length);
2815     unsigned end = std::min(std::max(start, m_compositionEnd), length);
2816     if (start >= end)
2817         return 0;
2818     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
2819 }
2820
2821 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
2822 {
2823     if (!m_compositionNode)
2824         return false;
2825     Position start = m_frame.selection().start();
2826     if (start.deprecatedNode() != m_compositionNode)
2827         return false;
2828     Position end = m_frame.selection().end();
2829     if (end.deprecatedNode() != m_compositionNode)
2830         return false;
2831
2832     if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
2833         return false;
2834     if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
2835         return false;
2836
2837     selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
2838     selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
2839     return true;
2840 }
2841
2842 void Editor::transpose()
2843 {
2844     if (!canEdit())
2845         return;
2846
2847     VisibleSelection selection = m_frame.selection().selection();
2848     if (!selection.isCaret())
2849         return;
2850
2851     // Make a selection that goes back one character and forward two characters.
2852     VisiblePosition caret = selection.visibleStart();
2853     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
2854     VisiblePosition previous = next.previous();
2855     if (next == previous)
2856         return;
2857     previous = previous.previous();
2858     if (!inSameParagraph(next, previous))
2859         return;
2860     RefPtr<Range> range = makeRange(previous, next);
2861     if (!range)
2862         return;
2863     VisibleSelection newSelection(range.get(), DOWNSTREAM);
2864
2865     // Transpose the two characters.
2866     String text = plainText(range.get());
2867     if (text.length() != 2)
2868         return;
2869     String transposed = text.right(1) + text.left(1);
2870
2871     // Select the two characters.
2872     if (newSelection != m_frame.selection().selection()) {
2873         if (!m_frame.selection().shouldChangeSelection(newSelection))
2874             return;
2875         m_frame.selection().setSelection(newSelection);
2876     }
2877
2878     // Insert the transposed characters.
2879     if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
2880         return;
2881     replaceSelectionWithText(transposed, false, false);
2882 }
2883
2884 void Editor::addToKillRing(Range* range, bool prepend)
2885 {
2886     if (m_shouldStartNewKillRingSequence)
2887         killRing().startNewSequence();
2888
2889     String text = plainText(range);
2890     if (prepend)
2891         killRing().prepend(text);
2892     else
2893         killRing().append(text);
2894     m_shouldStartNewKillRingSequence = false;
2895 }
2896
2897 void Editor::startAlternativeTextUITimer()
2898 {
2899     m_alternativeTextController->startAlternativeTextUITimer(AlternativeTextTypeCorrection);
2900 }
2901
2902 void Editor::handleAlternativeTextUIResult(const String& correction)
2903 {
2904     m_alternativeTextController->handleAlternativeTextUIResult(correction);
2905 }
2906
2907
2908 void Editor::dismissCorrectionPanelAsIgnored()
2909 {
2910     m_alternativeTextController->dismiss(ReasonForDismissingAlternativeTextIgnored);
2911 }
2912
2913 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection,  FrameSelection::SetSelectionOptions options)
2914 {
2915     // If the new selection is orphaned, then don't update the selection.
2916     if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
2917         return;
2918
2919     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
2920     // because there is work that it must do in this situation.
2921     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
2922     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
2923     bool selectionDidNotChangeDOMPosition = newSelection == m_frame.selection().selection();
2924     if (selectionDidNotChangeDOMPosition || m_frame.selection().shouldChangeSelection(newSelection))
2925         m_frame.selection().setSelection(newSelection, options);
2926
2927     // Some editing operations change the selection visually without affecting its position within the DOM.
2928     // For example when you press return in the following (the caret is marked by ^):
2929     // <div contentEditable="true"><div>^Hello</div></div>
2930     // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
2931     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
2932     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
2933     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
2934 #if PLATFORM(IOS)
2935     // FIXME: Merge this to open source https://bugs.webkit.org/show_bug.cgi?id=38830
2936     if (m_ignoreCompositionSelectionChange)
2937         return;
2938 #endif
2939     if (selectionDidNotChangeDOMPosition && client())
2940         client()->respondToChangedSelection(&m_frame);
2941 }
2942
2943 String Editor::selectedText() const
2944 {
2945     return selectedText(TextIteratorDefaultBehavior);
2946 }
2947
2948 String Editor::selectedTextForClipboard() const
2949 {
2950     if (m_frame.settings().selectionIncludesAltImageText())
2951         return selectedText(TextIteratorEmitsImageAltText);
2952     return selectedText();
2953 }
2954
2955 String Editor::selectedText(TextIteratorBehavior behavior) const
2956 {
2957     // We remove '\0' characters because they are not visibly rendered to the user.
2958     return plainText(m_frame.selection().toNormalizedRange().get(), behavior).replaceWithLiteral('\0', "");
2959 }
2960
2961 static inline void collapseCaretWidth(IntRect& rect)
2962 {
2963     // FIXME: Width adjustment doesn't work for rotated text.
2964     if (rect.width() == caretWidth)
2965         rect.setWidth(0);
2966     else if (rect.height() == caretWidth)
2967         rect.setHeight(0);
2968 }
2969
2970 IntRect Editor::firstRectForRange(Range* range) const
2971 {
2972     ASSERT(range->startContainer());
2973     ASSERT(range->endContainer());
2974
2975     VisiblePosition startVisiblePosition(range->startPosition(), DOWNSTREAM);
2976
2977     if (range->collapsed(ASSERT_NO_EXCEPTION)) {
2978         // FIXME: Getting caret rect and removing caret width is a very roundabout way to get collapsed range location.
2979         // In particular, width adjustment doesn't work for rotated text.
2980         IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect();
2981         collapseCaretWidth(startCaretRect);
2982         return startCaretRect;
2983     }
2984
2985     VisiblePosition endVisiblePosition(range->endPosition(), UPSTREAM);
2986
2987     if (inSameLine(startVisiblePosition, endVisiblePosition))
2988         return enclosingIntRect(RenderObject::absoluteBoundingBoxRectForRange(range));
2989
2990     LayoutUnit extraWidthToEndOfLine = 0;
2991     IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect(&extraWidthToEndOfLine);
2992     if (startCaretRect == IntRect())
2993         return IntRect();
2994
2995     // When start and end aren't on the same line, we want to go from start to the end of its line.
2996     bool textIsHorizontal = startCaretRect.width() == caretWidth;
2997     return textIsHorizontal ?
2998         IntRect(startCaretRect.x(),
2999             startCaretRect.y(),
3000             startCaretRect.width() + extraWidthToEndOfLine,
3001             startCaretRect.height()) :
3002         IntRect(startCaretRect.x(),
3003             startCaretRect.y(),
3004             startCaretRect.width(),
3005             startCaretRect.height() + extraWidthToEndOfLine);
3006 }
3007
3008 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
3009 {
3010 #if PLATFORM(IOS)
3011     if (m_frame.selectionChangeCallbacksDisabled())
3012         return true;
3013 #endif
3014     return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
3015 }
3016
3017 void Editor::computeAndSetTypingStyle(StyleProperties* style, EditAction editingAction)
3018 {
3019     if (!style || style->isEmpty()) {
3020         m_frame.selection().clearTypingStyle();
3021         return;
3022     }
3023
3024     // Calculate the current typing style.
3025     RefPtr<EditingStyle> typingStyle;
3026     if (m_frame.selection().typingStyle()) {
3027         typingStyle = m_frame.selection().typingStyle()->copy();
3028         typingStyle->overrideWithStyle(style);
3029     } else
3030         typingStyle = EditingStyle::create(style);
3031
3032     typingStyle->prepareToApplyAt(m_frame.selection().selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
3033
3034     // Handle block styles, substracting these from the typing style.
3035     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
3036     if (!blockStyle->isEmpty())
3037         applyCommand(ApplyStyleCommand::create(document(), blockStyle.get(), editingAction));
3038
3039     // Set the remaining style as the typing style.
3040     m_frame.selection().setTypingStyle(typingStyle);
3041 }
3042
3043 void Editor::textFieldDidBeginEditing(Element* e)
3044 {
3045     if (client())
3046         client()->textFieldDidBeginEditing(e);
3047 }
3048
3049 void Editor::textFieldDidEndEditing(Element* e)
3050 {
3051     dismissCorrectionPanelAsIgnored();
3052     if (client())
3053         client()->textFieldDidEndEditing(e);
3054 }
3055
3056 void Editor::textDidChangeInTextField(Element* e)
3057 {
3058     if (client())
3059         client()->textDidChangeInTextField(e);
3060 }
3061
3062 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
3063 {
3064     if (client())
3065         return client()->doTextFieldCommandFromEvent(e, ke);
3066
3067     return false;
3068 }
3069
3070 void Editor::textWillBeDeletedInTextField(Element* input)
3071 {
3072     if (client())
3073         client()->textWillBeDeletedInTextField(input);
3074 }
3075
3076 void Editor::textDidChangeInTextArea(Element* e)
3077 {
3078     if (client())
3079         client()->textDidChangeInTextArea(e);
3080 }
3081
3082 void Editor::applyEditingStyleToBodyElement() const
3083 {
3084     RefPtr<NodeList> list = document().getElementsByTagName("body");
3085     unsigned len = list->length();
3086     for (unsigned i = 0; i < len; i++)
3087         applyEditingStyleToElement(toElement(list->item(i)));
3088 }
3089
3090 void Editor::applyEditingStyleToElement(Element* element) const
3091 {
3092     if (!element)
3093         return;
3094     ASSERT(element->isStyledElement());
3095     if (!element->isStyledElement())
3096         return;
3097
3098     // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
3099     CSSStyleDeclaration* style = toStyledElement(element)->style();
3100     style->setPropertyInternal(CSSPropertyWordWrap, "break-word", false, IGNORE_EXCEPTION);
3101     style->setPropertyInternal(CSSPropertyWebkitNbspMode, "space", false, IGNORE_EXCEPTION);
3102     style->setPropertyInternal(CSSPropertyWebkitLineBreak, "after-white-space", false, IGNORE_EXCEPTION);
3103 }
3104
3105 bool Editor::findString(const String& target, FindOptions options)
3106 {
3107     VisibleSelection selection = m_frame.selection().selection();
3108
3109     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
3110
3111     if (!resultRange)
3112         return false;
3113
3114     m_frame.selection().setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
3115     m_frame.selection().revealSelection();
3116     return true;
3117 }
3118
3119 PassRefPtr<Range> Editor::findStringAndScrollToVisible(const String& target, Range* previousMatch, FindOptions options)
3120 {
3121     RefPtr<Range> nextMatch = rangeOfString(target, previousMatch, options);
3122     if (!nextMatch)
3123         return 0;
3124
3125     nextMatch->firstNode()->renderer()->scrollRectToVisible(nextMatch->boundingBox(),
3126         ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
3127
3128     return nextMatch.release();
3129 }
3130
3131 PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
3132 {
3133     if (target.isEmpty())
3134         return 0;
3135
3136     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
3137     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
3138     RefPtr<Range> searchRange(rangeOfContents(document()));
3139
3140     bool forward = !(options & Backwards);
3141     bool startInReferenceRange = referenceRange && (options & StartInSelection);
3142     if (referenceRange) {
3143         if (forward)
3144             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
3145         else
3146             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
3147     }
3148
3149     RefPtr<Node> shadowTreeRoot = referenceRange && referenceRange->startContainer() ? referenceRange->startContainer()->nonBoundaryShadowTreeRootNode() : 0;
3150     if (shadowTreeRoot) {
3151         if (forward)
3152             searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
3153         else
3154             searchRange->setStart(shadowTreeRoot.get(), 0);
3155     }
3156
3157     RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options));
3158     // If we started in the reference range and the found range exactly matches the reference range, find again.
3159     // Build a selection with the found range to remove collapsed whitespace.
3160     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
3161     if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
3162         searchRange = rangeOfContents(document());
3163         if (forward)
3164             searchRange->setStart(referenceRange->endPosition());
3165         else
3166             searchRange->setEnd(referenceRange->startPosition());
3167
3168         if (shadowTreeRoot) {
3169             if (forward)
3170                 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
3171             else
3172                 searchRange->setStart(shadowTreeRoot.get(), 0);
3173         }
3174
3175         resultRange = findPlainText(searchRange.get(), target, options);
3176     }
3177
3178     // If nothing was found in the shadow tree, search in main content following the shadow tree.
3179     if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && shadowTreeRoot) {
3180         searchRange = rangeOfContents(document());
3181         if (forward)
3182             searchRange->setStartAfter(shadowTreeRoot->shadowHost());
3183         else
3184             searchRange->setEndBefore(shadowTreeRoot->shadowHost());
3185
3186         resultRange = findPlainText(searchRange.get(), target, options);
3187     }
3188
3189     // If we didn't find anything and we're wrapping, search again in the entire document (this will
3190     // redundantly re-search the area already searched in some cases).
3191     if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && options & WrapAround) {
3192         searchRange = rangeOfContents(document());
3193         resultRange = findPlainText(searchRange.get(), target, options);
3194         // We used to return false here if we ended up with the same range that we started with
3195         // (e.g., the reference range was already the only instance of this text). But we decided that
3196         // this should be a success case instead, so we'll just fall through in that case.
3197     }
3198
3199     return resultRange->collapsed(ASSERT_NO_EXCEPTION) ? 0 : resultRange.release();
3200 }
3201
3202 static bool isFrameInRange(Frame* frame, Range* range)
3203 {
3204     bool inRange = false;
3205     for (HTMLFrameOwnerElement* ownerElement = frame->ownerElement(); ownerElement; ownerElement = ownerElement->document().ownerElement()) {
3206         if (&ownerElement->document() == &range->ownerDocument()) {
3207             inRange = range->intersectsNode(ownerElement, IGNORE_EXCEPTION);
3208             break;
3209         }
3210     }
3211     return inRange;
3212 }
3213
3214 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches, Vector<RefPtr<Range>>* matches)
3215 {
3216     if (target.isEmpty())
3217         return 0;
3218
3219     RefPtr<Range> searchRange;
3220     if (range) {
3221         if (&range->ownerDocument() == &document())
3222             searchRange = range;
3223         else if (!isFrameInRange(&m_frame, range))
3224             return 0;
3225     }
3226     if (!searchRange)
3227         searchRange = rangeOfContents(document());
3228
3229     Node* originalEndContainer = searchRange->endContainer();
3230     int originalEndOffset = searchRange->endOffset();
3231
3232     unsigned matchCount = 0;
3233     do {
3234         RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options & ~Backwards));
3235         if (resultRange->collapsed(IGNORE_EXCEPTION)) {
3236             if (!resultRange->startContainer()->isInShadowTree())
3237                 break;
3238
3239             searchRange->setStartAfter(resultRange->startContainer()->shadowHost(), IGNORE_EXCEPTION);
3240             searchRange->setEnd(originalEndContainer, originalEndOffset, IGNORE_EXCEPTION);
3241             continue;
3242         }
3243
3244         ++matchCount;
3245         if (matches)
3246             matches->append(resultRange);
3247         
3248         if (markMatches)
3249             document().markers().addMarker(resultRange.get(), DocumentMarker::TextMatch);
3250
3251         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
3252         if (limit > 0 && matchCount >= limit)
3253             break;
3254
3255         // Set the new start for the search range to be the end of the previous
3256         // result range. There is no need to use a VisiblePosition here,
3257         // since findPlainText will use a TextIterator to go over the visible
3258         // text nodes. 
3259         searchRange->setStart(resultRange->endContainer(IGNORE_EXCEPTION), resultRange->endOffset(IGNORE_EXCEPTION), IGNORE_EXCEPTION);
3260
3261         Node* shadowTreeRoot = searchRange->shadowRoot();
3262         if (searchRange->collapsed(IGNORE_EXCEPTION) && shadowTreeRoot)
3263             searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), IGNORE_EXCEPTION);
3264     } while (true);
3265
3266     if (markMatches || matches) {
3267         // Do a "fake" paint in order to execute the code that computes the rendered rect for each text match.
3268         if (m_frame.view() && m_frame.contentRenderer()) {
3269             document().updateLayout(); // Ensure layout is up to date.
3270             LayoutRect visibleRect = m_frame.view()->visibleContentRect();
3271             if (!visibleRect.isEmpty()) {
3272                 GraphicsContext context((PlatformGraphicsContext*)0);
3273                 context.setPaintingDisabled(true);
3274
3275                 PaintBehavior oldBehavior = m_frame.view()->paintBehavior();
3276                 m_frame.view()->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
3277                 m_frame.view()->paintContents(&context, enclosingIntRect(visibleRect));
3278                 m_frame.view()->setPaintBehavior(oldBehavior);
3279             }
3280         }
3281     }
3282
3283     return matchCount;
3284 }
3285
3286 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
3287 {
3288     if (flag == m_areMarkedTextMatchesHighlighted)
3289         return;
3290
3291     m_areMarkedTextMatchesHighlighted = flag;
3292     document().markers().repaintMarkers(DocumentMarker::TextMatch);
3293 }
3294
3295 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
3296 {
3297     m_alternativeTextController->stopPendingCorrection(oldSelection);
3298
3299     bool closeTyping = options & FrameSelection::CloseTyping;
3300     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
3301     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
3302     if (isContinuousSpellCheckingEnabled) {
3303         VisibleSelection newAdjacentWords;
3304         VisibleSelection newSelectedSentence;
3305         bool caretBrowsing = m_frame.settings().caretBrowsingEnabled();
3306         if (m_frame.selection().selection().isContentEditable() || caretBrowsing) {
3307             VisiblePosition newStart(m_frame.selection().selection().visibleStart());
3308 #if !PLATFORM(IOS)
3309             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
3310 #else
3311             // If this bug gets fixed, this PLATFORM(IOS) code could be removed:
3312             // <rdar://problem/7259611> Word boundary code on iPhone gives different results than desktop
3313             EWordSide startWordSide = LeftWordIfOnBoundary;
3314             UChar32 c = newStart.characterBefore();
3315             // FIXME: VisiblePosition::characterAfter() and characterBefore() do not emit newlines the same
3316             // way as TextIterator, so we do an isStartOfParagraph check here.
3317             if (isSpaceOrNewline(c) || c == 0xA0 || isStartOfParagraph(newStart)) {
3318                 startWordSide = RightWordIfOnBoundary;
3319             }
3320             newAdjacentWords = VisibleSelection(startOfWord(newStart, startWordSide), endOfWord(newStart, RightWordIfOnBoundary));
3321 #endif // !PLATFORM(IOS)
3322             if (isContinuousGrammarCheckingEnabled)
3323                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
3324         }
3325
3326         // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
3327         bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
3328
3329         // When typing we check spelling elsewhere, so don't redo it here.
3330         // If this is a change in selection resulting from a delete operation,
3331         // oldSelection may no longer be in the document.
3332         if (shouldCheckSpellingAndGrammar && closeTyping && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
3333             VisiblePosition oldStart(oldSelection.visibleStart());
3334             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
3335             if (oldAdjacentWords != newAdjacentWords) {
3336                 if (isContinuousGrammarCheckingEnabled) {
3337                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
3338                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
3339                 } else
3340                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
3341             }
3342         }
3343
3344         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
3345             if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3346                 document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3347         }
3348         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
3349             if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3350                 document().markers().removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3351         }
3352     }
3353
3354     // When continuous spell checking is off, existing markers disappear after the selection changes.
3355     if (!isContinuousSpellCheckingEnabled)
3356         document().markers().removeMarkers(DocumentMarker::Spelling);
3357     if (!isContinuousGrammarCheckingEnabled)
3358         document().markers().removeMarkers(DocumentMarker::Grammar);
3359
3360     notifyComponentsOnChangedSelection(oldSelection, options);
3361 }
3362
3363 static Node* findFirstMarkable(Node* node)
3364 {
3365     while (node) {
3366         if (!node->renderer())
3367             return 0;
3368         if (node->renderer()->isTextOrLineBreak())
3369             return node;
3370         if (isHTMLTextFormControlElement(*node))
3371             node = toHTMLTextFormControlElement(node)->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3372         else if (node->firstChild())
3373             node = node->firstChild();
3374         else
3375             node = node->nextSibling();
3376     }
3377
3378     return 0;
3379 }
3380
3381 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3382 {
3383     Node* node = findFirstMarkable(m_frame.selection().start().deprecatedNode());
3384     if (!node)
3385         return false;
3386
3387     unsigned int startOffset = static_cast<unsigned int>(from);
3388     unsigned int endOffset = static_cast<unsigned int>(from + length);
3389     Vector<DocumentMarker*> markers = document().markers().markersFor(node);
3390     for (size_t i = 0; i < markers.size(); ++i) {
3391         DocumentMarker* marker = markers[i];
3392         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3393             return true;
3394     }
3395
3396     return false;
3397 }       
3398
3399 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
3400 {
3401     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3402     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3403 #if !PLATFORM(IOS)
3404     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3405     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3406 #endif
3407
3408     TextCheckingTypeMask checkingTypes = 0;
3409     if (shouldMarkSpelling)
3410         checkingTypes |= TextCheckingTypeSpelling;
3411     if (shouldMarkGrammar)
3412         checkingTypes |= TextCheckingTypeGrammar;
3413 #if !PLATFORM(IOS)
3414     if (shouldCheckForCorrection)
3415         checkingTypes |= TextCheckingTypeCorrection;
3416     if (shouldShowCorrectionPanel)
3417         checkingTypes |= TextCheckingTypeShowCorrectionPanel;
3418
3419 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3420     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3421     if (shouldPerformReplacement) {
3422         if (isAutomaticLinkDetectionEnabled())
3423             checkingTypes |= TextCheckingTypeLink;
3424         if (isAutomaticQuoteSubstitutionEnabled())
3425             checkingTypes |= TextCheckingTypeQuote;
3426         if (isAutomaticDashSubstitutionEnabled())
3427             checkingTypes |= TextCheckingTypeDash;
3428         if (isAutomaticTextReplacementEnabled())
3429             checkingTypes |= TextCheckingTypeReplacement;
3430         if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3431             checkingTypes |= TextCheckingTypeCorrection;
3432     }
3433 #endif
3434 #endif // !PLATFORM(IOS)
3435
3436     return checkingTypes;
3437 }
3438
3439 void Editor::deviceScaleFactorChanged()
3440 {
3441 #if ENABLE(DELETION_UI)
3442     m_deleteButtonController->deviceScaleFactorChanged();
3443 #endif
3444 }
3445
3446 bool Editor::unifiedTextCheckerEnabled() const
3447 {
3448     return WebCore::unifiedTextCheckerEnabled(&m_frame);
3449 }
3450
3451 Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker* marker)
3452 {
3453     return m_alternativeTextController->dictationAlternativesForMarker(marker);
3454 }
3455
3456 void Editor::applyDictationAlternativelternative(const String& alternativeString)
3457 {
3458     m_alternativeTextController->applyDictationAlternative(alternativeString);
3459 }
3460
3461 void Editor::toggleOverwriteModeEnabled()
3462 {
3463     m_overwriteModeEnabled = !m_overwriteModeEnabled;
3464     m_frame.selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
3465 }
3466
3467 Document& Editor::document() const
3468 {
3469     ASSERT(m_frame.document());
3470     return *m_frame.document();
3471 }
3472
3473 } // namespace WebCore