c95dfaffa4a20f258ae0e06f8354d31c794c5c1e
[WebKit-https.git] / WebCore / editing / Editor.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3  * Copyright (C) 2007 Trolltech ASA
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 "ApplyStyleCommand.h"
32 #include "CSSComputedStyleDeclaration.h"
33 #include "CSSProperty.h"
34 #include "CSSPropertyNames.h"
35 #include "ClipboardEvent.h"
36 #include "DeleteButtonController.h"
37 #include "DeleteSelectionCommand.h"
38 #include "DocumentFragment.h"
39 #include "EditorClient.h"
40 #include "EventHandler.h"
41 #include "EventNames.h"
42 #include "FocusController.h"
43 #include "Frame.h"
44 #include "FrameView.h"
45 #include "HTMLInputElement.h"
46 #include "HTMLTextAreaElement.h"
47 #include "HitTestResult.h"
48 #include "IndentOutdentCommand.h"
49 #include "InsertListCommand.h"
50 #include "KeyboardEvent.h"
51 #include "ModifySelectionListLevel.h"
52 #include "Page.h"
53 #include "Pasteboard.h"
54 #include "RemoveFormatCommand.h"
55 #include "ReplaceSelectionCommand.h"
56 #include "Sound.h"
57 #include "Text.h"
58 #include "TextIterator.h"
59 #include "TypingCommand.h"
60 #include "htmlediting.h"
61 #include "markup.h"
62 #include "visible_units.h"
63
64 namespace WebCore {
65
66 using namespace std;
67 using namespace EventNames;
68 using namespace HTMLNames;
69
70 // When an event handler has moved the selection outside of a text control
71 // we should use the target control's selection for this editing operation.
72 Selection Editor::selectionForCommand(Event* event)
73 {
74     Selection selection = m_frame->selectionController()->selection();
75     if (!event)
76         return selection;
77     // If the target is a text control, and the current selection is outside of its shadow tree,
78     // then use the saved selection for that text control.
79     Node* target = event->target()->toNode();
80     Node* selectionStart = selection.start().node();
81     if (target && (!selectionStart || target->shadowAncestorNode() != selectionStart->shadowAncestorNode())) {
82         if (target->hasTagName(inputTag) && static_cast<HTMLInputElement*>(target)->isTextField())
83             return static_cast<HTMLInputElement*>(target)->selection();
84         if (target->hasTagName(textareaTag))
85             return static_cast<HTMLTextAreaElement*>(target)->selection();
86     }
87     return selection;
88 }
89
90 EditorClient* Editor::client() const
91 {
92     if (Page* page = m_frame->page())
93         return page->editorClient();
94     return 0;
95 }
96
97 void Editor::handleKeyboardEvent(KeyboardEvent* event)
98 {
99     if (EditorClient* c = client())
100         if (selectionForCommand(event).isContentEditable())
101             c->handleKeyboardEvent(event);
102 }
103
104 void Editor::handleInputMethodKeydown(KeyboardEvent* event)
105 {
106     if (EditorClient* c = client())
107         if (selectionForCommand(event).isContentEditable())
108             c->handleInputMethodKeydown(event);
109 }
110
111 bool Editor::canEdit() const
112 {
113     return m_frame->selectionController()->isContentEditable();
114 }
115
116 bool Editor::canEditRichly() const
117 {
118     return m_frame->selectionController()->isContentRichlyEditable();
119 }
120
121 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
122 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
123 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
124 // normally selectable to implement copy/paste (like divs, or a document body).
125
126 bool Editor::canDHTMLCut()
127 {
128     return !m_frame->selectionController()->isInPasswordField() && !dispatchCPPEvent(beforecutEvent, ClipboardNumb);
129 }
130
131 bool Editor::canDHTMLCopy()
132 {
133     return !m_frame->selectionController()->isInPasswordField() && !dispatchCPPEvent(beforecopyEvent, ClipboardNumb);
134 }
135
136 bool Editor::canDHTMLPaste()
137 {
138     return !dispatchCPPEvent(beforepasteEvent, ClipboardNumb);
139 }
140
141 bool Editor::canCut() const
142 {
143     return canCopy() && canDelete();
144 }
145
146 static HTMLImageElement* imageElementFromImageDocument(Document* document)
147 {
148     if (!document)
149         return 0;
150     if (!document->isImageDocument())
151         return 0;
152     
153     HTMLElement* body = document->body();
154     if (!body)
155         return 0;
156     
157     Node* node = body->firstChild();
158     if (!node)
159         return 0;    
160     if (!node->hasTagName(imgTag))
161         return 0;
162     return static_cast<HTMLImageElement*>(node);
163 }
164
165 bool Editor::canCopy() const
166 {
167     if (imageElementFromImageDocument(m_frame->document()))
168         return true;
169     SelectionController* selectionController = m_frame->selectionController();
170     return selectionController->isRange() && !selectionController->isInPasswordField();
171 }
172
173 bool Editor::canPaste() const
174 {
175     return canEdit();
176 }
177
178 bool Editor::canDelete() const
179 {
180     SelectionController* selectionController = m_frame->selectionController();
181     return selectionController->isRange() && selectionController->isContentEditable();
182 }
183
184 bool Editor::canDeleteRange(Range* range) const
185 {
186     ExceptionCode ec = 0;
187     Node* startContainer = range->startContainer(ec);
188     Node* endContainer = range->endContainer(ec);
189     if (!startContainer || !endContainer)
190         return false;
191     
192     if (!startContainer->isContentEditable() || !endContainer->isContentEditable())
193         return false;
194     
195     if (range->collapsed(ec)) {
196         VisiblePosition start(startContainer, range->startOffset(ec), DOWNSTREAM);
197         VisiblePosition previous = start.previous();
198         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
199         if (previous.isNull() || previous.deepEquivalent().node()->rootEditableElement() != startContainer->rootEditableElement())
200             return false;
201     }
202     return true;
203 }
204
205 bool Editor::smartInsertDeleteEnabled()
206 {   
207     return client() && client()->smartInsertDeleteEnabled();
208 }
209     
210 bool Editor::canSmartCopyOrDelete()
211 {
212     return client() && client()->smartInsertDeleteEnabled() && m_frame->selectionGranularity() == WordGranularity;
213 }
214
215 bool Editor::deleteWithDirection(SelectionController::EDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
216 {
217     // Delete the selection, if there is one.
218     // If not, make a selection using the passed-in direction and granularity.
219
220     if (!canEdit())
221         return false;
222
223     if (m_frame->selectionController()->isRange()) {
224         if (killRing)
225             addToKillRing(selectedRange().get(), false);
226         if (isTypingAction) {
227             if (m_frame->document()) {
228                 TypingCommand::deleteKeyPressed(m_frame->document(), canSmartCopyOrDelete(), granularity);
229                 revealSelectionAfterEditingOperation();
230             }
231         } else {
232             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
233             // Implicitly calls revealSelectionAfterEditingOperation().
234         }
235     } else {
236         SelectionController selectionToDelete;
237         selectionToDelete.setSelection(m_frame->selectionController()->selection());
238         selectionToDelete.modify(SelectionController::EXTEND, direction, granularity);
239         if (killRing && selectionToDelete.isCaret() && granularity != CharacterGranularity)
240             selectionToDelete.modify(SelectionController::EXTEND, direction, CharacterGranularity);
241
242         RefPtr<Range> range = selectionToDelete.toRange();
243
244         if (killRing)
245             addToKillRing(range.get(), false);
246
247         if (!m_frame->selectionController()->setSelectedRange(range.get(), DOWNSTREAM, (granularity != CharacterGranularity)))
248             return true;
249
250         switch (direction) {
251             case SelectionController::FORWARD:
252             case SelectionController::RIGHT:
253                 if (m_frame->document())
254                     TypingCommand::forwardDeleteKeyPressed(m_frame->document(), false, granularity);
255                 break;
256             case SelectionController::BACKWARD:
257             case SelectionController::LEFT:
258                 if (m_frame->document())
259                     TypingCommand::deleteKeyPressed(m_frame->document(), false, granularity);
260                 break;
261         }
262         revealSelectionAfterEditingOperation();
263     }
264
265     // clear the "start new kill ring sequence" setting, because it was set to true
266     // when the selection was updated by deleting the range
267     if (killRing)
268         setStartNewKillRingSequence(false);
269
270     return true;
271 }
272
273 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
274 {
275     if (m_frame->selectionController()->isNone())
276         return;
277     
278     applyCommand(new DeleteSelectionCommand(m_frame->document(), smartDelete));
279 }
280
281 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard)
282 {
283     String text = pasteboard->plainText(m_frame);
284     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
285         replaceSelectionWithText(text, false, canSmartReplaceWithPasteboard(pasteboard));
286 }
287
288 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
289 {
290     RefPtr<Range> range = selectedRange();
291     bool chosePlainText;
292     RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, range, allowPlainText, chosePlainText);
293     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
294         replaceSelectionWithFragment(fragment, false, canSmartReplaceWithPasteboard(pasteboard), chosePlainText);
295 }
296
297 bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
298 {
299     return client() && client()->smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
300 }
301
302 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
303 {
304     if (!client())
305         return false;
306         
307     Node* child = fragment->firstChild();
308     if (child && fragment->lastChild() == child && child->isCharacterDataNode())
309         return client()->shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);
310
311     return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
312 }
313
314 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
315 {
316     if (m_frame->selectionController()->isNone() || !fragment)
317         return;
318     
319     applyCommand(new ReplaceSelectionCommand(m_frame->document(), fragment, selectReplacement, smartReplace, matchStyle));
320     revealSelectionAfterEditingOperation();
321 }
322
323 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
324 {
325     replaceSelectionWithFragment(createFragmentFromText(selectedRange().get(), text), selectReplacement, smartReplace, true); 
326 }
327
328 PassRefPtr<Range> Editor::selectedRange()
329 {
330     if (!m_frame)
331         return 0;
332     return m_frame->selectionController()->toRange();
333 }
334
335 bool Editor::shouldDeleteRange(Range* range) const
336 {
337     ExceptionCode ec;
338     if (!range || range->collapsed(ec))
339         return false;
340     
341     if (!canDeleteRange(range))
342         return false;
343
344     return client() && client()->shouldDeleteRange(range);
345 }
346
347 bool Editor::tryDHTMLCopy()
348 {   
349     if (m_frame->selectionController()->isInPasswordField())
350         return false;
351
352     // Must be done before oncopy adds types and data to the pboard,
353     // also done for security, as it erases data from the last copy/paste.
354     Pasteboard::generalPasteboard()->clear();
355
356     return !dispatchCPPEvent(copyEvent, ClipboardWritable);
357 }
358
359 bool Editor::tryDHTMLCut()
360 {
361     if (m_frame->selectionController()->isInPasswordField())
362         return false;
363
364     // Must be done before oncut adds types and data to the pboard,
365     // also done for security, as it erases data from the last copy/paste.
366     Pasteboard::generalPasteboard()->clear();
367
368     return !dispatchCPPEvent(cutEvent, ClipboardWritable);
369 }
370
371 bool Editor::tryDHTMLPaste()
372 {
373     return !dispatchCPPEvent(pasteEvent, ClipboardReadable);
374 }
375
376 void Editor::writeSelectionToPasteboard(Pasteboard* pasteboard)
377 {
378     pasteboard->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame);
379 }
380
381 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
382 {
383     return client() && client()->shouldInsertText(text, range, action);
384 }
385
386 bool Editor::shouldShowDeleteInterface(HTMLElement* element) const
387 {
388     return client() && client()->shouldShowDeleteInterface(element);
389 }
390
391 void Editor::respondToChangedSelection(const Selection& oldSelection)
392 {
393     if (client())
394         client()->respondToChangedSelection();
395     m_deleteButtonController->respondToChangedSelection(oldSelection);
396 }
397
398 void Editor::respondToChangedContents(const Selection& endingSelection)
399 {
400     if (AXObjectCache::accessibilityEnabled()) {
401         Node* node = endingSelection.start().node();
402         if (node)
403             m_frame->renderer()->document()->axObjectCache()->postNotification(node->renderer(), "AXValueChanged");
404     }
405     
406     if (client())
407         client()->respondToChangedContents();  
408 }
409
410 const SimpleFontData* Editor::fontForSelection(bool& hasMultipleFonts) const
411 {
412 #if !PLATFORM(QT)
413     hasMultipleFonts = false;
414
415     if (!m_frame->selectionController()->isRange()) {
416         Node* nodeToRemove;
417         RenderStyle* style = m_frame->styleForSelectionStart(nodeToRemove); // sets nodeToRemove
418
419         const SimpleFontData* result = 0;
420         if (style)
421             result = style->font().primaryFont();
422         
423         if (nodeToRemove) {
424             ExceptionCode ec;
425             nodeToRemove->remove(ec);
426             ASSERT(ec == 0);
427         }
428
429         return result;
430     }
431
432     const SimpleFontData* font = 0;
433
434     RefPtr<Range> range = m_frame->selectionController()->toRange();
435     Node* startNode = range->editingStartPosition().node();
436     if (startNode) {
437         Node* pastEnd = range->pastEndNode();
438         // In the loop below, n should eventually match pastEnd and not become nil, but we've seen at least one
439         // unreproducible case where this didn't happen, so check for nil also.
440         for (Node* n = startNode; n && n != pastEnd; n = n->traverseNextNode()) {
441             RenderObject *renderer = n->renderer();
442             if (!renderer)
443                 continue;
444             // FIXME: Are there any node types that have renderers, but that we should be skipping?
445             const SimpleFontData* f = renderer->style()->font().primaryFont();
446             if (!font)
447                 font = f;
448             else if (font != f) {
449                 hasMultipleFonts = true;
450                 break;
451             }
452         }
453     }
454
455     return font;
456 #else
457     return 0;
458 #endif
459 }
460
461 TriState Editor::selectionUnorderedListState() const
462 {
463     if (m_frame->selectionController()->isCaret()) {
464         if (enclosingNodeWithTag(m_frame->selectionController()->selection().start(), ulTag))
465             return TrueTriState;
466     } else if (m_frame->selectionController()->isRange()) {
467         Node* startNode = enclosingNodeWithTag(m_frame->selectionController()->selection().start(), ulTag);
468         Node* endNode = enclosingNodeWithTag(m_frame->selectionController()->selection().end(), ulTag);
469         if (startNode && endNode && startNode == endNode)
470             return TrueTriState;
471     }
472
473     return FalseTriState;
474 }
475
476 TriState Editor::selectionOrderedListState() const
477 {
478     if (m_frame->selectionController()->isCaret()) {
479         if (enclosingNodeWithTag(m_frame->selectionController()->selection().start(), olTag))
480             return TrueTriState;
481     } else if (m_frame->selectionController()->isRange()) {
482         Node* startNode = enclosingNodeWithTag(m_frame->selectionController()->selection().start(), olTag);
483         Node* endNode = enclosingNodeWithTag(m_frame->selectionController()->selection().end(), olTag);
484         if (startNode && endNode && startNode == endNode)
485             return TrueTriState;
486     }
487
488     return FalseTriState;
489 }
490
491 PassRefPtr<Node> Editor::insertOrderedList()
492 {
493     if (!canEditRichly())
494         return 0;
495         
496     RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::OrderedList);
497     revealSelectionAfterEditingOperation();
498     return newList;
499 }
500
501 PassRefPtr<Node> Editor::insertUnorderedList()
502 {
503     if (!canEditRichly())
504         return 0;
505         
506     RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::UnorderedList);
507     revealSelectionAfterEditingOperation();
508     return newList;
509 }
510
511 bool Editor::canIncreaseSelectionListLevel()
512 {
513     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(m_frame->document());
514 }
515
516 bool Editor::canDecreaseSelectionListLevel()
517 {
518     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(m_frame->document());
519 }
520
521 PassRefPtr<Node> Editor::increaseSelectionListLevel()
522 {
523     if (!canEditRichly() || m_frame->selectionController()->isNone())
524         return 0;
525     
526     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(m_frame->document());
527     revealSelectionAfterEditingOperation();
528     return newList;
529 }
530
531 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
532 {
533     if (!canEditRichly() || m_frame->selectionController()->isNone())
534         return 0;
535     
536     PassRefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(m_frame->document());
537     revealSelectionAfterEditingOperation();
538     return newList;
539 }
540
541 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
542 {
543     if (!canEditRichly() || m_frame->selectionController()->isNone())
544         return 0;
545     
546     PassRefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(m_frame->document());
547     revealSelectionAfterEditingOperation();
548     return newList;
549 }
550
551 void Editor::decreaseSelectionListLevel()
552 {
553     if (!canEditRichly() || m_frame->selectionController()->isNone())
554         return;
555     
556     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(m_frame->document());
557     revealSelectionAfterEditingOperation();
558 }
559
560 void Editor::removeFormattingAndStyle()
561 {
562     applyCommand(new RemoveFormatCommand(m_frame->document()));
563 }
564
565 void Editor::setLastEditCommand(PassRefPtr<EditCommand> lastEditCommand) 
566 {
567     m_lastEditCommand = lastEditCommand;
568 }
569
570 // Returns whether caller should continue with "the default processing", which is the same as 
571 // the event handler NOT setting the return value to false
572 bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy)
573 {
574     Node* target = m_frame->selectionController()->start().element();
575     if (!target && m_frame->document())
576         target = m_frame->document()->body();
577     if (!target)
578         return true;
579     target = target->shadowAncestorNode();
580     
581     RefPtr<Clipboard> clipboard = newGeneralClipboard(policy);
582
583     ExceptionCode ec = 0;
584     RefPtr<Event> evt = new ClipboardEvent(eventType, true, true, clipboard.get());
585     EventTargetNodeCast(target)->dispatchEvent(evt, ec, true);
586     bool noDefaultProcessing = evt->defaultPrevented();
587
588     // invalidate clipboard here for security
589     clipboard->setAccessPolicy(ClipboardNumb);
590     
591     return !noDefaultProcessing;
592 }
593
594 void Editor::applyStyle(CSSStyleDeclaration* style, EditAction editingAction)
595 {
596     switch (m_frame->selectionController()->state()) {
597         case Selection::NONE:
598             // do nothing
599             break;
600         case Selection::CARET:
601             m_frame->computeAndSetTypingStyle(style, editingAction);
602             break;
603         case Selection::RANGE:
604             if (m_frame->document() && style)
605                 applyCommand(new ApplyStyleCommand(m_frame->document(), style, editingAction));
606             break;
607     }
608 }
609     
610 bool Editor::shouldApplyStyle(CSSStyleDeclaration* style, Range* range)
611 {   
612     return client()->shouldApplyStyle(style, range);
613 }
614     
615 void Editor::applyParagraphStyle(CSSStyleDeclaration* style, EditAction editingAction)
616 {
617     switch (m_frame->selectionController()->state()) {
618         case Selection::NONE:
619             // do nothing
620             break;
621         case Selection::CARET:
622         case Selection::RANGE:
623             if (m_frame->document() && style)
624                 applyCommand(new ApplyStyleCommand(m_frame->document(), style, editingAction, ApplyStyleCommand::ForceBlockProperties));
625             break;
626     }
627 }
628
629 void Editor::applyStyleToSelection(CSSStyleDeclaration* style, EditAction editingAction)
630 {
631     if (!style || style->length() == 0 || !canEditRichly())
632         return;
633
634     if (client() && client()->shouldApplyStyle(style, m_frame->selectionController()->toRange().get()))
635         applyStyle(style, editingAction);
636 }
637
638 void Editor::applyParagraphStyleToSelection(CSSStyleDeclaration* style, EditAction editingAction)
639 {
640     if (!style || style->length() == 0 || !canEditRichly())
641         return;
642     
643     if (client() && client()->shouldApplyStyle(style, m_frame->selectionController()->toRange().get()))
644         applyParagraphStyle(style, editingAction);
645 }
646
647 bool Editor::clientIsEditable() const
648 {
649     return client() && client()->isEditable();
650 }
651
652 bool Editor::selectionStartHasStyle(CSSStyleDeclaration* style) const
653 {
654     Node* nodeToRemove;
655     RefPtr<CSSComputedStyleDeclaration> selectionStyle = m_frame->selectionComputedStyle(nodeToRemove);
656     if (!selectionStyle)
657         return false;
658     
659     RefPtr<CSSMutableStyleDeclaration> mutableStyle = style->makeMutable();
660     
661     bool match = true;
662     DeprecatedValueListConstIterator<CSSProperty> end;
663     for (DeprecatedValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
664         int propertyID = (*it).id();
665         if (!equalIgnoringCase(mutableStyle->getPropertyValue(propertyID), selectionStyle->getPropertyValue(propertyID))) {
666             match = false;
667             break;
668         }
669     }
670     
671     if (nodeToRemove) {
672         ExceptionCode ec = 0;
673         nodeToRemove->remove(ec);
674         ASSERT(ec == 0);
675     }
676     
677     return match;
678 }
679
680 static void updateState(CSSMutableStyleDeclaration* desiredStyle, CSSComputedStyleDeclaration* computedStyle, bool& atStart, TriState& state)
681 {
682     DeprecatedValueListConstIterator<CSSProperty> end;
683     for (DeprecatedValueListConstIterator<CSSProperty> it = desiredStyle->valuesIterator(); it != end; ++it) {
684         int propertyID = (*it).id();
685         String desiredProperty = desiredStyle->getPropertyValue(propertyID);
686         String computedProperty = computedStyle->getPropertyValue(propertyID);
687         TriState propertyState = equalIgnoringCase(desiredProperty, computedProperty)
688             ? TrueTriState : FalseTriState;
689         if (atStart) {
690             state = propertyState;
691             atStart = false;
692         } else if (state != propertyState) {
693             state = MixedTriState;
694             break;
695         }
696     }
697 }
698
699 TriState Editor::selectionHasStyle(CSSStyleDeclaration* style) const
700 {
701     bool atStart = true;
702     TriState state = FalseTriState;
703
704     RefPtr<CSSMutableStyleDeclaration> mutableStyle = style->makeMutable();
705
706     if (!m_frame->selectionController()->isRange()) {
707         Node* nodeToRemove;
708         RefPtr<CSSComputedStyleDeclaration> selectionStyle = m_frame->selectionComputedStyle(nodeToRemove);
709         if (!selectionStyle)
710             return FalseTriState;
711         updateState(mutableStyle.get(), selectionStyle.get(), atStart, state);
712         if (nodeToRemove) {
713             ExceptionCode ec = 0;
714             nodeToRemove->remove(ec);
715             ASSERT(ec == 0);
716         }
717     } else {
718         for (Node* node = m_frame->selectionController()->start().node(); node; node = node->traverseNextNode()) {
719             RefPtr<CSSComputedStyleDeclaration> computedStyle = new CSSComputedStyleDeclaration(node);
720             if (computedStyle)
721                 updateState(mutableStyle.get(), computedStyle.get(), atStart, state);
722             if (state == MixedTriState)
723                 break;
724             if (node == m_frame->selectionController()->end().node())
725                 break;
726         }
727     }
728
729     return state;
730 }
731 void Editor::indent()
732 {
733     applyCommand(new IndentOutdentCommand(m_frame->document(), IndentOutdentCommand::Indent));
734 }
735
736 void Editor::outdent()
737 {
738     applyCommand(new IndentOutdentCommand(m_frame->document(), IndentOutdentCommand::Outdent));
739 }
740
741 static void dispatchEditableContentChangedEvents(const EditCommand& command)
742 {
743     Element* startRoot = command.startingRootEditableElement();
744     Element* endRoot = command.endingRootEditableElement();
745     ExceptionCode ec;
746     if (startRoot)
747         startRoot->dispatchEvent(new Event(webkitEditableContentChangedEvent, false, false), ec, true);
748     if (endRoot && endRoot != startRoot)
749         endRoot->dispatchEvent(new Event(webkitEditableContentChangedEvent, false, false), ec, true);
750 }
751
752 void Editor::appliedEditing(PassRefPtr<EditCommand> cmd)
753 {
754     dispatchEditableContentChangedEvents(*cmd);
755     
756     // FIXME: We shouldn't tell setSelection to clear the typing style or removed anchor here.
757     // If we didn't, we wouldn't have to save/restore the removedAnchor, and we wouldn't have to have
758     // the typing style stored in two places (the Frame and commands).
759     RefPtr<Node> anchor = removedAnchor();
760     
761     Selection newSelection(cmd->endingSelection());
762     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
763     // because there is work that it must do in this situation.
764     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
765     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
766     if (newSelection == m_frame->selectionController()->selection() || m_frame->shouldChangeSelection(newSelection))
767         m_frame->selectionController()->setSelection(newSelection, false);
768     
769     setRemovedAnchor(anchor);
770     
771     // Now set the typing style from the command. Clear it when done.
772     // This helps make the case work where you completely delete a piece
773     // of styled text and then type a character immediately after.
774     // That new character needs to take on the style of the just-deleted text.
775     // FIXME: Improve typing style.
776     // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
777     if (cmd->typingStyle()) {
778         m_frame->setTypingStyle(cmd->typingStyle());
779         cmd->setTypingStyle(0);
780     }
781     
782     // Command will be equal to last edit command only in the case of typing
783     if (m_lastEditCommand.get() == cmd)
784         ASSERT(cmd->isTypingCommand());
785     else {
786         // Only register a new undo command if the command passed in is
787         // different from the last command
788         m_lastEditCommand = cmd;
789         if (client())
790             client()->registerCommandForUndo(m_lastEditCommand);
791     }
792     respondToChangedContents(newSelection);    
793 }
794
795 void Editor::unappliedEditing(PassRefPtr<EditCommand> cmd)
796 {
797     dispatchEditableContentChangedEvents(*cmd);
798     
799     Selection newSelection(cmd->startingSelection());
800     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
801     // because there is work that it must do in this situation.
802     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
803     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
804     if (newSelection == m_frame->selectionController()->selection() || m_frame->shouldChangeSelection(newSelection))
805         m_frame->selectionController()->setSelection(newSelection, true);
806     
807     m_lastEditCommand = 0;
808     if (client())
809         client()->registerCommandForRedo(cmd);
810     respondToChangedContents(newSelection);    
811 }
812
813 void Editor::reappliedEditing(PassRefPtr<EditCommand> cmd)
814 {
815     dispatchEditableContentChangedEvents(*cmd);
816     
817     Selection newSelection(cmd->endingSelection());
818     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
819     // because there is work that it must do in this situation.
820     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
821     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
822     if (newSelection == m_frame->selectionController()->selection() || m_frame->shouldChangeSelection(newSelection))
823         m_frame->selectionController()->setSelection(newSelection, true);
824     
825     m_lastEditCommand = 0;
826     if (client())
827         client()->registerCommandForUndo(cmd);
828     respondToChangedContents(newSelection);    
829 }
830
831 Editor::Editor(Frame* frame)
832     : m_frame(frame)
833     , m_deleteButtonController(new DeleteButtonController(frame))
834     , m_ignoreCompositionSelectionChange(false)
835     , m_shouldStartNewKillRingSequence(false)
836
837 }
838
839 Editor::~Editor()
840 {
841 }
842
843 void Editor::clear()
844 {
845     m_compositionNode = 0;
846     m_customCompositionUnderlines.clear();
847 }
848
849 bool Editor::insertText(const String& text, Event* triggeringEvent)
850 {
851     return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
852 }
853
854 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, Event* triggeringEvent)
855 {
856     if (text.isEmpty())
857         return false;
858
859     Selection selection = selectionForCommand(triggeringEvent);
860     if (!selection.isContentEditable())
861         return false;
862     RefPtr<Range> range = selection.toRange();
863
864     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
865         return true;
866
867     // Get the selection to use for the event that triggered this insertText.
868     // If the event handler changed the selection, we may want to use a different selection
869     // that is contained in the event target.
870     selection = selectionForCommand(triggeringEvent);
871     if (selection.isContentEditable()) {
872         if (Node* selectionStart = selection.start().node()) {
873             RefPtr<Document> document = selectionStart->document();
874             
875             // Insert the text
876             TypingCommand::insertText(document.get(), text, selection, selectInsertedText);
877
878             // Reveal the current selection 
879             if (Frame* editedFrame = document->frame())
880                 if (Page* page = editedFrame->page())
881                     page->focusController()->focusedOrMainFrame()->revealSelection(RenderLayer::gAlignToEdgeIfNeeded);
882         }
883     }
884
885     return true;
886 }
887
888 bool Editor::insertLineBreak()
889 {
890     if (!canEdit())
891         return false;
892
893     if (!shouldInsertText("\n", m_frame->selectionController()->toRange().get(), EditorInsertActionTyped))
894         return true;
895
896     TypingCommand::insertLineBreak(m_frame->document());
897     revealSelectionAfterEditingOperation();
898     return true;
899 }
900
901 bool Editor::insertParagraphSeparator()
902 {
903     if (!canEdit())
904         return false;
905
906     if (!canEditRichly())
907         return insertLineBreak();
908
909     if (!shouldInsertText("\n", m_frame->selectionController()->toRange().get(), EditorInsertActionTyped))
910         return true;
911
912     TypingCommand::insertParagraphSeparator(m_frame->document());
913     revealSelectionAfterEditingOperation();
914     return true;
915 }
916
917 void Editor::cut()
918 {
919     if (tryDHTMLCut())
920         return; // DHTML did the whole operation
921     if (!canCut()) {
922         systemBeep();
923         return;
924     }
925     RefPtr<Range> selection = selectedRange();
926     if (shouldDeleteRange(selection.get())) {
927         Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame);
928         didWriteSelectionToPasteboard();
929         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
930     }
931 }
932
933 void Editor::copy()
934 {
935     if (tryDHTMLCopy())
936         return; // DHTML did the whole operation
937     if (!canCopy()) {
938         systemBeep();
939         return;
940     }
941     
942     Document* document = m_frame->document();
943     if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
944         Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
945     else
946         Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame);
947     
948     didWriteSelectionToPasteboard();
949 }
950
951 #if !PLATFORM(MAC)
952
953 void Editor::paste()
954 {
955     ASSERT(m_frame->document());
956     if (tryDHTMLPaste())
957         return;     // DHTML did the whole operation
958     if (!canPaste())
959         return;
960     DocLoader* loader = m_frame->document()->docLoader();
961     loader->setAllowStaleResources(true);
962     if (m_frame->selectionController()->isContentRichlyEditable())
963         pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
964     else
965         pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
966     loader->setAllowStaleResources(false);
967 }
968
969 #endif
970
971 void Editor::pasteAsPlainText()
972 {
973    if (!canPaste())
974         return;
975    pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
976 }
977
978 void Editor::performDelete()
979 {
980     if (!canDelete()) {
981         systemBeep();
982         return;
983     }
984
985     addToKillRing(selectedRange().get(), false);
986     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
987
988     // clear the "start new kill ring sequence" setting, because it was set to true
989     // when the selection was updated by deleting the range
990     setStartNewKillRingSequence(false);
991 }
992
993 void Editor::copyURL(const KURL& url, const String& title)
994 {
995     Pasteboard::generalPasteboard()->writeURL(url, title, m_frame);
996 }
997
998 void Editor::copyImage(const HitTestResult& result)
999 {
1000     KURL url = result.absoluteLinkURL();
1001     if (url.isEmpty())
1002         url = result.absoluteImageURL();
1003
1004     Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
1005 }
1006
1007 bool Editor::isContinuousSpellCheckingEnabled()
1008 {
1009     return client() && client()->isContinuousSpellCheckingEnabled();
1010 }
1011
1012 void Editor::toggleContinuousSpellChecking()
1013 {
1014     if (client())
1015         client()->toggleContinuousSpellChecking();
1016 }
1017
1018 bool Editor::isGrammarCheckingEnabled()
1019 {
1020     return client() && client()->isGrammarCheckingEnabled();
1021 }
1022
1023 void Editor::toggleGrammarChecking()
1024 {
1025     if (client())
1026         client()->toggleGrammarChecking();
1027 }
1028
1029 int Editor::spellCheckerDocumentTag()
1030 {
1031     return client() ? client()->spellCheckerDocumentTag() : 0;
1032 }
1033
1034 bool Editor::shouldEndEditing(Range* range)
1035 {
1036     return client() && client()->shouldEndEditing(range);
1037 }
1038
1039 bool Editor::shouldBeginEditing(Range* range)
1040 {
1041     return client() && client()->shouldBeginEditing(range);
1042 }
1043
1044 void Editor::clearUndoRedoOperations()
1045 {
1046     if (client())
1047         client()->clearUndoRedoOperations();
1048 }
1049
1050 bool Editor::canUndo()
1051 {
1052     return client() && client()->canUndo();
1053 }
1054
1055 void Editor::undo()
1056 {
1057     if (client())
1058         client()->undo();
1059 }
1060
1061 bool Editor::canRedo()
1062 {
1063     return client() && client()->canRedo();
1064 }
1065
1066 void Editor::redo()
1067 {
1068     if (client())
1069         client()->redo();
1070 }
1071
1072 void Editor::didBeginEditing()
1073 {
1074     if (client())
1075         client()->didBeginEditing();
1076 }
1077
1078 void Editor::didEndEditing()
1079 {
1080     if (client())
1081         client()->didEndEditing();
1082 }
1083
1084 void Editor::didWriteSelectionToPasteboard()
1085 {
1086     if (client())
1087         client()->didWriteSelectionToPasteboard();
1088 }
1089
1090 void Editor::toggleBold()
1091 {
1092     command("ToggleBold").execute();
1093 }
1094
1095 void Editor::toggleUnderline()
1096 {
1097     command("ToggleUnderline").execute();
1098 }
1099
1100 void Editor::setBaseWritingDirection(const String& direction)
1101 {
1102     ExceptionCode ec = 0;
1103
1104     RefPtr<CSSMutableStyleDeclaration> style = new CSSMutableStyleDeclaration;
1105     style->setProperty(CSS_PROP_DIRECTION, direction, false, ec);
1106     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1107 }
1108
1109 void Editor::selectComposition()
1110 {
1111     RefPtr<Range> range = compositionRange();
1112     if (!range)
1113         return;
1114     
1115     // The composition can start inside a composed character sequence, so we have to override checks.
1116     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1117     Selection selection;
1118     selection.setWithoutValidation(range->startPosition(), range->endPosition());
1119     m_frame->selectionController()->setSelection(selection, false, false);
1120 }
1121
1122 void Editor::confirmComposition()
1123 {
1124     if (!m_compositionNode)
1125         return;
1126     confirmComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), false);
1127 }
1128
1129 void Editor::confirmCompositionWithoutDisturbingSelection()
1130 {
1131     if (!m_compositionNode)
1132         return;
1133     confirmComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), true);
1134 }
1135
1136 void Editor::confirmComposition(const String& text)
1137 {
1138     confirmComposition(text, false);
1139 }
1140
1141 void Editor::confirmComposition(const String& text, bool preserveSelection)
1142 {
1143     setIgnoreCompositionSelectionChange(true);
1144
1145     Selection oldSelection = m_frame->selectionController()->selection();
1146
1147     selectComposition();
1148
1149     if (m_frame->selectionController()->isNone()) {
1150         setIgnoreCompositionSelectionChange(false);
1151         return;
1152     }
1153     
1154     // If there is a composition to replace, remove it with a deletion that will be part of the
1155     // same Undo step as the next and previous insertions.
1156     TypingCommand::deleteSelection(m_frame->document(), false);
1157
1158     m_compositionNode = 0;
1159     m_customCompositionUnderlines.clear();
1160
1161     insertText(text, 0);
1162
1163     if (preserveSelection)
1164         m_frame->selectionController()->setSelection(oldSelection, false, false);
1165
1166     setIgnoreCompositionSelectionChange(false);
1167 }
1168
1169 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1170 {
1171     setIgnoreCompositionSelectionChange(true);
1172
1173     selectComposition();
1174
1175     if (m_frame->selectionController()->isNone()) {
1176         setIgnoreCompositionSelectionChange(false);
1177         return;
1178     }
1179     
1180     // If there is a composition to replace, remove it with a deletion that will be part of the
1181     // same Undo step as the next and previous insertions.
1182     TypingCommand::deleteSelection(m_frame->document(), false);
1183
1184     m_compositionNode = 0;
1185     m_customCompositionUnderlines.clear();
1186
1187     if (!text.isEmpty()) {
1188         TypingCommand::insertText(m_frame->document(), text, true, true);
1189
1190         Node* baseNode = m_frame->selectionController()->base().node();
1191         unsigned baseOffset = m_frame->selectionController()->base().offset();
1192         Node* extentNode = m_frame->selectionController()->extent().node();
1193         unsigned extentOffset = m_frame->selectionController()->extent().offset();
1194
1195         if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
1196             m_compositionNode = static_cast<Text*>(baseNode);
1197             m_compositionStart = baseOffset;
1198             m_compositionEnd = extentOffset;
1199             m_customCompositionUnderlines = underlines;
1200             size_t numUnderlines = m_customCompositionUnderlines.size();
1201             for (size_t i = 0; i < numUnderlines; ++i) {
1202                 m_customCompositionUnderlines[i].startOffset += baseOffset;
1203                 m_customCompositionUnderlines[i].endOffset += baseOffset;
1204             }
1205             if (baseNode->renderer())
1206                 baseNode->renderer()->repaint();
1207
1208             unsigned start = min(baseOffset + selectionStart, extentOffset);
1209             unsigned end = min(max(start, baseOffset + selectionEnd), extentOffset);
1210             RefPtr<Range> selectedRange = new Range(baseNode->document(), baseNode, start, baseNode, end);                
1211             m_frame->selectionController()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1212         }
1213     }
1214
1215     setIgnoreCompositionSelectionChange(false);
1216 }
1217
1218 void Editor::ignoreSpelling()
1219 {
1220     if (!client())
1221         return;
1222
1223     String text = frame()->selectedText();
1224     ASSERT(text.length() != 0);
1225     client()->ignoreWordInSpellDocument(text);
1226 }
1227
1228 void Editor::learnSpelling()
1229 {
1230     if (!client())
1231         return;
1232
1233     String text = frame()->selectedText();
1234     ASSERT(text.length() != 0);
1235     client()->learnWord(text);
1236 }
1237
1238 static String findFirstMisspellingInRange(EditorClient* client, Range* searchRange, int& firstMisspellingOffset, bool markAll)
1239 {
1240     ASSERT_ARG(client, client);
1241     ASSERT_ARG(searchRange, searchRange);
1242     
1243     WordAwareIterator it(searchRange);
1244     firstMisspellingOffset = 0;
1245     
1246     String firstMisspelling;
1247     int currentChunkOffset = 0;
1248
1249     while (!it.atEnd()) {
1250         const UChar* chars = it.characters();
1251         int len = it.length();
1252         
1253         // Skip some work for one-space-char hunks
1254         if (!(len == 1 && chars[0] == ' ')) {
1255             
1256             int misspellingLocation = -1;
1257             int misspellingLength = 0;
1258             client->checkSpellingOfString(chars, len, &misspellingLocation, &misspellingLength);
1259
1260             // 5490627 shows that there was some code path here where the String constructor below crashes.
1261             // We don't know exactly what combination of bad input caused this, so we're making this much
1262             // more robust against bad input on release builds.
1263             ASSERT(misspellingLength >= 0);
1264             ASSERT(misspellingLocation >= -1);
1265             ASSERT(misspellingLength == 0 || misspellingLocation >= 0);
1266             ASSERT(misspellingLocation < len);
1267             ASSERT(misspellingLength <= len);
1268             ASSERT(misspellingLocation + misspellingLength <= len);
1269             
1270             if (misspellingLocation >= 0 && misspellingLength > 0 && misspellingLocation < len && misspellingLength <= len && misspellingLocation + misspellingLength <= len) {
1271                 
1272                 // Remember first-encountered misspelling and its offset
1273                 if (!firstMisspelling) {
1274                     firstMisspellingOffset = currentChunkOffset + misspellingLocation;
1275                     firstMisspelling = String(chars + misspellingLocation, misspellingLength);
1276                 }
1277                 
1278                 // Mark this instance if we're marking all instances. Otherwise bail out because we found the first one.
1279                 if (!markAll)
1280                     break;
1281                 
1282                 // Compute range of misspelled word
1283                 RefPtr<Range> misspellingRange = TextIterator::subrange(searchRange, currentChunkOffset + misspellingLocation, misspellingLength);
1284                 
1285                 // Store marker for misspelled word
1286                 ExceptionCode ec = 0;
1287                 misspellingRange->startContainer(ec)->document()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
1288                 ASSERT(ec == 0);
1289             }
1290         }
1291         
1292         currentChunkOffset += len;
1293         it.advance();
1294     }
1295     
1296     return firstMisspelling;
1297 }
1298
1299 #ifndef BUILDING_ON_TIGER
1300
1301 static PassRefPtr<Range> paragraphAlignedRangeForRange(Range* arbitraryRange, int& offsetIntoParagraphAlignedRange, String& paragraphString)
1302 {
1303     ASSERT_ARG(arbitraryRange, arbitraryRange);
1304     
1305     ExceptionCode ec = 0;
1306     
1307     // Expand range to paragraph boundaries
1308     RefPtr<Range> paragraphRange = arbitraryRange->cloneRange(ec);
1309     setStart(paragraphRange.get(), startOfParagraph(arbitraryRange->startPosition()));
1310     setEnd(paragraphRange.get(), endOfParagraph(arbitraryRange->endPosition()));
1311     
1312     // Compute offset from start of expanded range to start of original range
1313     RefPtr<Range> offsetAsRange = new Range(paragraphRange->startContainer(ec)->document(), paragraphRange->startPosition(), arbitraryRange->startPosition());
1314     offsetIntoParagraphAlignedRange = TextIterator::rangeLength(offsetAsRange.get());
1315     
1316     // Fill in out parameter with string representing entire paragraph range.
1317     // Someday we might have a caller that doesn't use this, but for now all callers do.
1318     paragraphString = plainText(paragraphRange.get());
1319
1320     return paragraphRange;
1321 }
1322
1323 static int findFirstGrammarDetailInRange(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int badGrammarPhraseLength, Range *searchRange, int startOffset, int endOffset, bool markAll)
1324 {
1325     // Found some bad grammar. Find the earliest detail range that starts in our search range (if any).
1326     // Optionally add a DocumentMarker for each detail in the range.
1327     int earliestDetailLocationSoFar = -1;
1328     int earliestDetailIndex = -1;
1329     for (unsigned i = 0; i < grammarDetails.size(); i++) {
1330         const GrammarDetail* detail = &grammarDetails[i];
1331         ASSERT(detail->length > 0 && detail->location >= 0);
1332         
1333         int detailStartOffsetInParagraph = badGrammarPhraseLocation + detail->location;
1334         
1335         // Skip this detail if it starts before the original search range
1336         if (detailStartOffsetInParagraph < startOffset)
1337             continue;
1338         
1339         // Skip this detail if it starts after the original search range
1340         if (detailStartOffsetInParagraph >= endOffset)
1341             continue;
1342         
1343         if (markAll) {
1344             RefPtr<Range> badGrammarRange = TextIterator::subrange(searchRange, badGrammarPhraseLocation - startOffset + detail->location, detail->length);
1345             ExceptionCode ec = 0;
1346             badGrammarRange->startContainer(ec)->document()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription);
1347             ASSERT(ec == 0);
1348         }
1349         
1350         // Remember this detail only if it's earlier than our current candidate (the details aren't in a guaranteed order)
1351         if (earliestDetailIndex < 0 || earliestDetailLocationSoFar > detail->location) {
1352             earliestDetailIndex = i;
1353             earliestDetailLocationSoFar = detail->location;
1354         }
1355     }
1356     
1357     return earliestDetailIndex;
1358 }
1359     
1360 static String findFirstBadGrammarInRange(EditorClient* client, Range* searchRange, GrammarDetail& outGrammarDetail, int& outGrammarPhraseOffset, bool markAll)
1361 {
1362     ASSERT_ARG(client, client);
1363     ASSERT_ARG(searchRange, searchRange);
1364     
1365     // Initialize out parameters; these will be updated if we find something to return.
1366     outGrammarDetail.location = -1;
1367     outGrammarDetail.length = 0;
1368     outGrammarDetail.guesses.clear();
1369     outGrammarDetail.userDescription = "";
1370     outGrammarPhraseOffset = 0;
1371     
1372     String firstBadGrammarPhrase;
1373
1374     // Expand the search range to encompass entire paragraphs, since grammar checking needs that much context.
1375     // Determine the character offset from the start of the paragraph to the start of the original search range,
1376     // since we will want to ignore results in this area.
1377     int searchRangeStartOffset;
1378     String paragraphString;
1379     RefPtr<Range> paragraphRange = paragraphAlignedRangeForRange(searchRange, searchRangeStartOffset, paragraphString);
1380         
1381     // Determine the character offset from the start of the paragraph to the end of the original search range, 
1382     // since we will want to ignore results in this area also.
1383     int searchRangeEndOffset = searchRangeStartOffset + TextIterator::rangeLength(searchRange);
1384         
1385     // Start checking from beginning of paragraph, but skip past results that occur before the start of the original search range.
1386     int startOffset = 0;
1387     while (startOffset < searchRangeEndOffset) {
1388         Vector<GrammarDetail> grammarDetails;
1389         int badGrammarPhraseLocation = -1;
1390         int badGrammarPhraseLength = 0;
1391         client->checkGrammarOfString(paragraphString.characters() + startOffset, paragraphString.length() - startOffset, grammarDetails, &badGrammarPhraseLocation, &badGrammarPhraseLength);
1392         
1393         if (badGrammarPhraseLength == 0) {
1394             ASSERT(badGrammarPhraseLocation == -1);
1395             return String();
1396         }
1397
1398         ASSERT(badGrammarPhraseLocation >= 0);
1399         badGrammarPhraseLocation += startOffset;
1400
1401         
1402         // Found some bad grammar. Find the earliest detail range that starts in our search range (if any).
1403         int badGrammarIndex = findFirstGrammarDetailInRange(grammarDetails, badGrammarPhraseLocation, badGrammarPhraseLength, searchRange, searchRangeStartOffset, searchRangeEndOffset, markAll);
1404         if (badGrammarIndex >= 0) {
1405             ASSERT(static_cast<unsigned>(badGrammarIndex) < grammarDetails.size());
1406             outGrammarDetail = grammarDetails[badGrammarIndex];
1407         }
1408
1409         // If we found a detail in range, then we have found the first bad phrase (unless we found one earlier but
1410         // kept going so we could mark all instances).
1411         if (badGrammarIndex >= 0 && firstBadGrammarPhrase.isEmpty()) {
1412             outGrammarPhraseOffset = badGrammarPhraseLocation - searchRangeStartOffset;
1413             firstBadGrammarPhrase = paragraphString.substring(badGrammarPhraseLocation, badGrammarPhraseLength);
1414             
1415             // Found one. We're done now, unless we're marking each instance.
1416             if (!markAll)
1417                 break;
1418         }
1419
1420         // These results were all between the start of the paragraph and the start of the search range; look
1421         // beyond this phrase.
1422         startOffset = badGrammarPhraseLocation + badGrammarPhraseLength;
1423     }
1424     
1425     return firstBadGrammarPhrase;
1426 }
1427     
1428 #endif /* not BUILDING_ON_TIGER */
1429
1430 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1431 {
1432     ExceptionCode ec = 0;
1433
1434     // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1435     // then we wrap and search from the doc start to (approximately) where we started.
1436     
1437     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
1438     // repeated "check spelling" commands work.
1439     Selection selection(frame()->selectionController()->selection());
1440     RefPtr<Range> spellingSearchRange(rangeOfContents(frame()->document()));
1441     bool startedWithSelection = false;
1442     if (selection.start().node()) {
1443         startedWithSelection = true;
1444         if (startBeforeSelection) {
1445             VisiblePosition start(selection.visibleStart());
1446             // We match AppKit's rule: Start 1 character before the selection.
1447             VisiblePosition oneBeforeStart = start.previous();
1448             setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1449         } else
1450             setStart(spellingSearchRange.get(), selection.visibleEnd());
1451     }
1452
1453     Position position = spellingSearchRange->startPosition();
1454     if (!isEditablePosition(position)) {
1455         // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1456         // selection is editable.
1457         // This can happen in Mail for a mix of non-editable and editable content (like Stationary), 
1458         // when spell checking the whole document before sending the message.
1459         // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1460
1461         position = firstEditablePositionAfterPositionInRoot(position, frame()->document()->documentElement()).deepEquivalent();
1462         if (position.isNull())
1463             return;
1464         
1465         Position rangeCompliantPosition = rangeCompliantEquivalent(position);
1466         spellingSearchRange->setStart(rangeCompliantPosition.node(), rangeCompliantPosition.offset(), ec);
1467         startedWithSelection = false;   // won't need to wrap
1468     }
1469     
1470     // topNode defines the whole range we want to operate on 
1471     Node* topNode = highestEditableRoot(position);
1472     spellingSearchRange->setEnd(topNode, maxDeepOffset(topNode), ec);
1473
1474     // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1475     // at a word boundary. Going back by one char and then forward by a word does the trick.
1476     if (startedWithSelection) {
1477         VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1478         if (oneBeforeStart.isNotNull()) {
1479             setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1480         } // else we were already at the start of the editable node
1481     }
1482     
1483     if (spellingSearchRange->collapsed(ec))
1484         return;       // nothing to search in
1485     
1486     // Get the spell checker if it is available
1487     if (!client())
1488         return;
1489         
1490     // We go to the end of our first range instead of the start of it, just to be sure
1491     // we don't get foiled by any word boundary problems at the start.  It means we might
1492     // do a tiny bit more searching.
1493     Node *searchEndNodeAfterWrap = spellingSearchRange->endContainer(ec);
1494     int searchEndOffsetAfterWrap = spellingSearchRange->endOffset(ec);
1495     
1496     int misspellingOffset;
1497     String misspelledWord = findFirstMisspellingInRange(client(), spellingSearchRange.get(), misspellingOffset, false);
1498     
1499     String badGrammarPhrase;
1500
1501 #ifndef BUILDING_ON_TIGER
1502     int grammarPhraseOffset = 0;
1503     GrammarDetail grammarDetail;
1504
1505     // Search for bad grammar that occurs prior to the next misspelled word (if any)
1506     RefPtr<Range> grammarSearchRange = spellingSearchRange->cloneRange(ec);
1507     if (!misspelledWord.isEmpty()) {
1508         // Stop looking at start of next misspelled word
1509         CharacterIterator chars(grammarSearchRange.get());
1510         chars.advance(misspellingOffset);
1511         grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1512     }
1513     
1514     if (isGrammarCheckingEnabled())
1515         badGrammarPhrase = findFirstBadGrammarInRange(client(), grammarSearchRange.get(), grammarDetail, grammarPhraseOffset, false);
1516 #endif
1517     
1518     // 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
1519     // block rather than at a selection).
1520     if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
1521         spellingSearchRange->setStart(topNode, 0, ec);
1522         // going until the end of the very first chunk we tested is far enough
1523         spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, ec);
1524         
1525         misspelledWord = findFirstMisspellingInRange(client(), spellingSearchRange.get(), misspellingOffset, false);
1526
1527 #ifndef BUILDING_ON_TIGER
1528         grammarSearchRange = spellingSearchRange->cloneRange(ec);
1529         if (!misspelledWord.isEmpty()) {
1530             // Stop looking at start of next misspelled word
1531             CharacterIterator chars(grammarSearchRange.get());
1532             chars.advance(misspellingOffset);
1533             grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1534         }
1535         if (isGrammarCheckingEnabled())
1536             badGrammarPhrase = findFirstBadGrammarInRange(client(), grammarSearchRange.get(), grammarDetail, grammarPhraseOffset, false);
1537 #endif
1538     }
1539     
1540     if (!badGrammarPhrase.isEmpty()) {
1541 #ifdef BUILDING_ON_TIGER
1542         ASSERT_NOT_REACHED();
1543 #else
1544         // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
1545         // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
1546         // panel, and store a marker so we draw the green squiggle later.
1547         
1548         ASSERT(badGrammarPhrase.length() > 0);
1549         ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
1550         
1551         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
1552         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
1553         frame()->selectionController()->setSelection(Selection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
1554         frame()->revealSelection();
1555         
1556         client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
1557         frame()->document()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
1558 #endif        
1559     } else if (!misspelledWord.isEmpty()) {
1560         // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
1561         // a marker so we draw the red squiggle later.
1562         
1563         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
1564         frame()->selectionController()->setSelection(Selection(misspellingRange.get(), DOWNSTREAM));
1565         frame()->revealSelection();
1566         
1567         client()->updateSpellingUIWithMisspelledWord(misspelledWord);
1568         frame()->document()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
1569     }
1570 }
1571
1572 bool Editor::isSelectionMisspelled()
1573 {
1574     String selectedString = frame()->selectedText();
1575     int length = selectedString.length();
1576     if (length == 0)
1577         return false;
1578
1579     if (!client())
1580         return false;
1581     
1582     int misspellingLocation = -1;
1583     int misspellingLength = 0;
1584     client()->checkSpellingOfString(selectedString.characters(), length, &misspellingLocation, &misspellingLength);
1585     
1586     // The selection only counts as misspelled if the selected text is exactly one misspelled word
1587     if (misspellingLength != length)
1588         return false;
1589     
1590     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
1591     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
1592     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
1593     // or a grammar error.
1594     client()->updateSpellingUIWithMisspelledWord(selectedString);
1595     
1596     return true;
1597 }
1598
1599 #ifndef BUILDING_ON_TIGER
1600 static bool isRangeUngrammatical(EditorClient* client, Range *range, Vector<String>& guessesVector)
1601 {
1602     if (!client)
1603         return false;
1604
1605     ExceptionCode ec;
1606     if (!range || range->collapsed(ec))
1607         return false;
1608     
1609     // Returns true only if the passed range exactly corresponds to a bad grammar detail range. This is analogous
1610     // to isSelectionMisspelled. It's not good enough for there to be some bad grammar somewhere in the range,
1611     // or overlapping the range; the ranges must exactly match.
1612     guessesVector.clear();
1613     int grammarPhraseOffset;
1614     
1615     GrammarDetail grammarDetail;
1616     String badGrammarPhrase = findFirstBadGrammarInRange(client, range, grammarDetail, grammarPhraseOffset, false);    
1617     
1618     // No bad grammar in these parts at all.
1619     if (badGrammarPhrase.isEmpty())
1620         return false;
1621     
1622     // Bad grammar, but phrase (e.g. sentence) starts beyond start of range.
1623     if (grammarPhraseOffset > 0)
1624         return false;
1625     
1626     ASSERT(grammarDetail.location >= 0 && grammarDetail.length > 0);
1627     
1628     // Bad grammar, but start of detail (e.g. ungrammatical word) doesn't match start of range
1629     if (grammarDetail.location + grammarPhraseOffset != 0)
1630         return false;
1631     
1632     // Bad grammar at start of range, but end of bad grammar is before or after end of range
1633     if (grammarDetail.length != TextIterator::rangeLength(range))
1634         return false;
1635     
1636     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
1637     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
1638     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
1639     // or a grammar error.
1640     client->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
1641     
1642     return true;
1643 }
1644 #endif
1645
1646 bool Editor::isSelectionUngrammatical()
1647 {
1648 #ifdef BUILDING_ON_TIGER
1649     return false;
1650 #else
1651     Vector<String> ignoredGuesses;
1652     return isRangeUngrammatical(client(), frame()->selectionController()->toRange().get(), ignoredGuesses);
1653 #endif
1654 }
1655
1656 Vector<String> Editor::guessesForUngrammaticalSelection()
1657 {
1658 #ifdef BUILDING_ON_TIGER
1659     return Vector<String>();
1660 #else
1661     Vector<String> guesses;
1662     // Ignore the result of isRangeUngrammatical; we just want the guesses, whether or not there are any
1663     isRangeUngrammatical(client(), frame()->selectionController()->toRange().get(), guesses);
1664     return guesses;
1665 #endif
1666 }
1667
1668 Vector<String> Editor::guessesForMisspelledSelection()
1669 {
1670     String selectedString = frame()->selectedText();
1671     ASSERT(selectedString.length() != 0);
1672
1673     Vector<String> guesses;
1674     if (client())
1675         client()->getGuessesForWord(selectedString, guesses);
1676     return guesses;
1677 }
1678
1679 void Editor::showSpellingGuessPanel()
1680 {
1681     if (!client()) {
1682         LOG_ERROR("No NSSpellChecker");
1683         return;
1684     }
1685
1686 #ifndef BUILDING_ON_TIGER
1687     // Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
1688     // to match rest of OS X.
1689     if (client()->spellingUIIsShowing()) {
1690         client()->showSpellingUI(false);
1691         return;
1692     }
1693 #endif
1694     
1695     advanceToNextMisspelling(true);
1696     client()->showSpellingUI(true);
1697 }
1698
1699 bool Editor::spellingPanelIsShowing()
1700 {
1701     if (!client())
1702         return false;
1703     return client()->spellingUIIsShowing();
1704 }
1705
1706 void Editor::markMisspellingsAfterTypingToPosition(const VisiblePosition &p)
1707 {
1708     if (!isContinuousSpellCheckingEnabled())
1709         return;
1710     
1711     // Check spelling of one word
1712     markMisspellings(Selection(startOfWord(p, LeftWordIfOnBoundary), endOfWord(p, RightWordIfOnBoundary)));
1713     
1714     if (!isGrammarCheckingEnabled())
1715         return;
1716     
1717     // Check grammar of entire sentence
1718     markBadGrammar(Selection(startOfSentence(p), endOfSentence(p)));
1719 }
1720
1721 static void markAllMisspellingsInRange(EditorClient* client, Range* searchRange)
1722 {
1723     // Use the "markAll" feature of findFirstMisspellingInRange. Ignore the return value and the "out parameter";
1724     // all we need to do is mark every instance.
1725     int ignoredOffset;
1726     findFirstMisspellingInRange(client, searchRange, ignoredOffset, true);
1727 }
1728
1729 #ifndef BUILDING_ON_TIGER
1730 static void markAllBadGrammarInRange(EditorClient* client, Range* searchRange)
1731 {
1732     // Use the "markAll" feature of findFirstBadGrammarInRange. Ignore the return value and "out parameters"; all we need to
1733     // do is mark every instance.
1734     GrammarDetail ignoredGrammarDetail;
1735     int ignoredOffset;
1736     findFirstBadGrammarInRange(client, searchRange, ignoredGrammarDetail, ignoredOffset, true);
1737 }
1738 #endif
1739     
1740 static void markMisspellingsOrBadGrammar(Editor* editor, const Selection& selection, bool checkSpelling)
1741 {
1742     // This function is called with a selection already expanded to word boundaries.
1743     // Might be nice to assert that here.
1744     
1745     // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
1746     // grammar checking can only be on if spell checking is also on.
1747     if (!editor->isContinuousSpellCheckingEnabled())
1748         return;
1749     
1750     RefPtr<Range> searchRange(selection.toRange());
1751     if (!searchRange || searchRange->isDetached())
1752         return;
1753     
1754     // If we're not in an editable node, bail.
1755     int exception = 0;
1756     Node *editableNode = searchRange->startContainer(exception);
1757     if (!editableNode->isContentEditable())
1758         return;
1759     
1760     // Get the spell checker if it is available
1761     if (!editor->client())
1762         return;
1763     
1764     if (checkSpelling)
1765         markAllMisspellingsInRange(editor->client(), searchRange.get());
1766     else {
1767 #ifdef BUILDING_ON_TIGER
1768         ASSERT_NOT_REACHED();
1769 #else
1770         if (editor->isGrammarCheckingEnabled())
1771             markAllBadGrammarInRange(editor->client(), searchRange.get());
1772 #endif
1773     }    
1774 }
1775
1776 void Editor::markMisspellings(const Selection& selection)
1777 {
1778     markMisspellingsOrBadGrammar(this, selection, true);
1779 }
1780     
1781 void Editor::markBadGrammar(const Selection& selection)
1782 {
1783 #ifndef BUILDING_ON_TIGER
1784     markMisspellingsOrBadGrammar(this, selection, false);
1785 #endif
1786 }
1787
1788 PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
1789 {
1790     Document* document = m_frame->documentAtPoint(windowPoint);
1791     if (!document)
1792         return 0;
1793     
1794     Frame* frame = document->frame();
1795     ASSERT(frame);
1796     FrameView* frameView = frame->view();
1797     if (!frameView)
1798         return 0;
1799     IntPoint framePoint = frameView->windowToContents(windowPoint);
1800     Selection selection(frame->visiblePositionForPoint(framePoint));
1801     return avoidIntersectionWithNode(selection.toRange().get(), deleteButtonController() ? deleteButtonController()->containerElement() : 0);
1802 }
1803
1804 void Editor::revealSelectionAfterEditingOperation()
1805 {
1806     if (m_ignoreCompositionSelectionChange)
1807         return;
1808
1809     m_frame->revealSelection(RenderLayer::gAlignToEdgeIfNeeded);
1810 }
1811
1812 void Editor::setIgnoreCompositionSelectionChange(bool ignore)
1813 {
1814     if (m_ignoreCompositionSelectionChange == ignore)
1815         return;
1816
1817     m_ignoreCompositionSelectionChange = ignore;
1818     if (!ignore)
1819         revealSelectionAfterEditingOperation();
1820 }
1821
1822 PassRefPtr<Range> Editor::compositionRange() const
1823 {
1824     if (!m_compositionNode)
1825         return 0;
1826     unsigned length = m_compositionNode->length();
1827     unsigned start = min(m_compositionStart, length);
1828     unsigned end = min(max(start, m_compositionEnd), length);
1829     if (start >= end)
1830         return 0;
1831     return new Range(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
1832 }
1833
1834 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
1835 {
1836     if (!m_compositionNode)
1837         return false;
1838     Position start = m_frame->selectionController()->start();
1839     if (start.node() != m_compositionNode)
1840         return false;
1841     Position end = m_frame->selectionController()->end();
1842     if (end.node() != m_compositionNode)
1843         return false;
1844
1845     if (static_cast<unsigned>(start.offset()) < m_compositionStart)
1846         return false;
1847     if (static_cast<unsigned>(end.offset()) > m_compositionEnd)
1848         return false;
1849
1850     selectionStart = start.offset() - m_compositionStart;
1851     selectionEnd = start.offset() - m_compositionEnd;
1852     return true;
1853 }
1854
1855 void Editor::transpose()
1856 {
1857     if (!canEdit())
1858         return;
1859
1860      Selection selection = m_frame->selectionController()->selection();
1861      if (!selection.isCaret())
1862          return;
1863
1864     // Make a selection that goes back one character and forward two characters.
1865     VisiblePosition caret = selection.visibleStart();
1866     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
1867     VisiblePosition previous = next.previous();
1868     if (next == previous)
1869         return;
1870     previous = previous.previous();
1871     if (!inSameParagraph(next, previous))
1872         return;
1873     RefPtr<Range> range = makeRange(previous, next);
1874     if (!range)
1875         return;
1876     Selection newSelection(range.get(), DOWNSTREAM);
1877
1878     // Transpose the two characters.
1879     String text = plainText(range.get());
1880     if (text.length() != 2)
1881         return;
1882     String transposed = text.right(1) + text.left(1);
1883
1884     // Select the two characters.
1885     if (newSelection != m_frame->selectionController()->selection()) {
1886         if (!m_frame->shouldChangeSelection(newSelection))
1887             return;
1888         m_frame->selectionController()->setSelection(newSelection);
1889     }
1890
1891     // Insert the transposed characters.
1892     if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
1893         return;
1894     replaceSelectionWithText(transposed, false, false);
1895 }
1896
1897 void Editor::addToKillRing(Range* range, bool prepend)
1898 {
1899     if (m_shouldStartNewKillRingSequence)
1900         startNewKillRingSequence();
1901
1902     String text = plainText(range);
1903     text.replace('\\', m_frame->backslashAsCurrencySymbol());
1904     if (prepend)
1905         prependToKillRing(text);
1906     else
1907         appendToKillRing(text);
1908     m_shouldStartNewKillRingSequence = false;
1909 }
1910
1911 #if !PLATFORM(MAC)
1912
1913 void Editor::appendToKillRing(const String&)
1914 {
1915 }
1916
1917 void Editor::prependToKillRing(const String&)
1918 {
1919 }
1920
1921 String Editor::yankFromKillRing()
1922 {
1923     return String();
1924 }
1925
1926 void Editor::startNewKillRingSequence()
1927 {
1928 }
1929
1930 void Editor::setKillRingToYankedState()
1931 {
1932 }
1933
1934 #endif
1935
1936 } // namespace WebCore