2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
3 For licensing, see LICENSE.html or http://ckeditor.com/license
8 // #### checkSelectionChange : START
10 // The selection change check basically saves the element parent tree of
11 // the current node and check it on successive requests. If there is any
12 // change on the tree, then the selectionChange event gets fired.
13 function checkSelectionChange()
17 // In IE, the "selectionchange" event may still get thrown when
18 // releasing the WYSIWYG mode, so we need to check it first.
19 var sel = this.getSelection();
20 if ( !sel || !sel.document.getWindow().$ )
23 var firstElement = sel.getStartElement();
24 var currentPath = new CKEDITOR.dom.elementPath( firstElement );
26 if ( !currentPath.compare( this._.selectionPreviousPath ) )
28 this._.selectionPreviousPath = currentPath;
29 this.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );
36 var checkSelectionChangeTimer,
37 checkSelectionChangeTimeoutPending;
39 function checkSelectionChangeTimeout()
41 // Firing the "OnSelectionChange" event on every key press started to
42 // be too slow. This function guarantees that there will be at least
43 // 200ms delay between selection checks.
45 checkSelectionChangeTimeoutPending = true;
47 if ( checkSelectionChangeTimer )
50 checkSelectionChangeTimeoutExec.call( this );
52 checkSelectionChangeTimer = CKEDITOR.tools.setTimeout( checkSelectionChangeTimeoutExec, 200, this );
55 function checkSelectionChangeTimeoutExec()
57 checkSelectionChangeTimer = null;
59 if ( checkSelectionChangeTimeoutPending )
61 // Call this with a timeout so the browser properly moves the
62 // selection after the mouseup. It happened that the selection was
63 // being moved after the mouseup when clicking inside selected text
65 CKEDITOR.tools.setTimeout( checkSelectionChange, 0, this );
67 checkSelectionChangeTimeoutPending = false;
71 // #### checkSelectionChange : END
75 modes : { wysiwyg : 1, source : 1 },
76 exec : function( editor )
78 switch ( editor.mode )
81 editor.document.$.execCommand( 'SelectAll', false, null );
82 // Force triggering selectionChange (#7008)
83 editor.forceNextSelectionCheck();
84 editor.selectionChange();
87 // Select the contents of the textarea
88 var textarea = editor.textarea.$;
89 if ( CKEDITOR.env.ie )
90 textarea.createTextRange().execCommand( 'SelectAll' );
93 textarea.selectionStart = 0;
94 textarea.selectionEnd = textarea.value.length;
102 CKEDITOR.plugins.add( 'selection',
104 init : function( editor )
106 editor.on( 'contentDom', function()
108 var doc = editor.document,
109 body = doc.getBody(),
110 html = doc.getDocumentElement();
112 if ( CKEDITOR.env.ie )
114 // Other browsers don't loose the selection if the
115 // editor document loose the focus. In IE, we don't
116 // have support for it, so we reproduce it here, other
117 // than firing the selection change event.
123 // "onfocusin" is fired before "onfocus". It makes it
124 // possible to restore the selection before click
125 // events get executed.
126 body.on( 'focusin', function( evt )
128 // If there are elements with layout they fire this event but
129 // it must be ignored to allow edit its contents #4682
130 if ( evt.data.$.srcElement.nodeName != 'BODY' )
133 // If we have saved a range, restore it at this
137 // Range restored here might invalidate the DOM structure thus break up
138 // the locked selection, give it up. (#6083)
139 var lockedSelection = doc.getCustomData( 'cke_locked_selection' );
140 if ( restoreEnabled && !lockedSelection )
142 // Well not break because of this.
155 body.on( 'focus', function()
157 // Enable selections to be saved.
163 body.on( 'beforedeactivate', function( evt )
165 // Ignore this event if it's caused by focus switch between
166 // internal editable control type elements, e.g. layouted paragraph. (#4682)
167 if ( evt.data.$.toElement )
170 // Disable selections from being saved.
175 // IE before version 8 will leave cursor blinking inside the document after
176 // editor blurred unless we clean up the selection. (#4716)
177 if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
179 editor.on( 'blur', function( evt )
181 // Try/Catch to avoid errors if the editor is hidden. (#6375)
184 editor.document && editor.document.$.selection.empty();
190 // Listening on document element ensures that
191 // scrollbar is included. (#5280)
192 html.on( 'mousedown', function()
194 // Lock restore selection now, as we have
195 // a followed 'click' event which introduce
196 // new selection. (#5735)
200 html.on( 'mouseup', function()
205 // In IE6/7 the blinking cursor appears, but contents are
206 // not editable. (#5634)
207 if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.version < 8 || CKEDITOR.env.quirks ) )
209 // The 'click' event is not fired when clicking the
210 // scrollbars, so we can use it to check whether
211 // the empty space following <body> has been clicked.
212 html.on( 'click', function( evt )
214 if ( evt.data.getTarget().getName() == 'html' )
215 editor.getSelection().getRanges()[ 0 ].select();
220 // IE fires the "selectionchange" event when clicking
221 // inside a selection. We don't want to capture that.
222 body.on( 'mousedown', function( evt )
224 // IE scrolls document to top on right mousedown
225 // when editor has no focus, remember this scroll
226 // position and revert it before context menu opens. (#5778)
227 if ( evt.data.$.button == 2 )
229 var sel = editor.document.$.selection;
230 if ( sel.type == 'None' )
231 scroll = editor.window.getScrollPosition();
239 // Restore recorded scroll position when needed on right mouseup.
240 if ( evt.data.$.button == 2 && scroll )
242 editor.document.$.documentElement.scrollLeft = scroll.x;
243 editor.document.$.documentElement.scrollTop = scroll.y;
248 setTimeout( function()
250 saveSelection( true );
255 body.on( 'keydown', disableSave );
264 // IE is the only to provide the "selectionchange"
266 doc.on( 'selectionchange', saveSelection );
268 function disableSave()
273 function saveSelection( testIt )
277 var doc = editor.document,
278 sel = editor.getSelection(),
279 nativeSel = sel && sel.getNative();
281 // There is a very specific case, when clicking
282 // inside a text selection. In that case, the
283 // selection collapses at the clicking point,
284 // but the selection object remains in an
285 // unknown state, making createRange return a
286 // range at the very start of the document. In
287 // such situation we have to test the range, to
288 // be sure it's valid.
289 if ( testIt && nativeSel && nativeSel.type == 'None' )
291 // The "InsertImage" command can be used to
292 // test whether the selection is good or not.
293 // If not, it's enough to give some time to
294 // IE to put things in order for us.
295 if ( !doc.$.queryCommandEnabled( 'InsertImage' ) )
297 CKEDITOR.tools.setTimeout( saveSelection, 50, this, true );
302 // Avoid saving selection from within text input. (#5747)
304 if ( nativeSel && nativeSel.type && nativeSel.type != 'Control'
305 && ( parentTag = nativeSel.createRange() )
306 && ( parentTag = parentTag.parentElement() )
307 && ( parentTag = parentTag.nodeName )
308 && parentTag.toLowerCase() in { input: 1, textarea : 1 } )
313 savedRange = nativeSel && sel.getRanges()[ 0 ];
315 checkSelectionChangeTimeout.call( editor );
321 // In other browsers, we make the selection change
322 // check based on other events, like clicks or keys
325 doc.on( 'mouseup', checkSelectionChangeTimeout, editor );
326 doc.on( 'keyup', checkSelectionChangeTimeout, editor );
330 // Clear the cached range path before unload. (#7174)
331 editor.on( 'contentDomUnload', editor.forceNextSelectionCheck, editor );
333 editor.addCommand( 'selectAll', selectAllCmd );
334 editor.ui.addButton( 'SelectAll',
336 label : editor.lang.selectAll,
337 command : 'selectAll'
340 editor.selectionChange = checkSelectionChangeTimeout;
345 * Gets the current selection from the editing area when in WYSIWYG mode.
346 * @returns {CKEDITOR.dom.selection} A selection object or null if not on
347 * WYSIWYG mode or no selection is available.
349 * var selection = CKEDITOR.instances.editor1.<b>getSelection()</b>;
350 * alert( selection.getType() );
352 CKEDITOR.editor.prototype.getSelection = function()
354 return this.document && this.document.getSelection();
357 CKEDITOR.editor.prototype.forceNextSelectionCheck = function()
359 delete this._.selectionPreviousPath;
363 * Gets the current selection from the document.
364 * @returns {CKEDITOR.dom.selection} A selection object.
366 * var selection = CKEDITOR.instances.editor1.document.<b>getSelection()</b>;
367 * alert( selection.getType() );
369 CKEDITOR.dom.document.prototype.getSelection = function()
371 var sel = new CKEDITOR.dom.selection( this );
372 return ( !sel || sel.isInvalid ) ? null : sel;
379 * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_NONE )
380 * alert( 'Nothing is selected' );
382 CKEDITOR.SELECTION_NONE = 1;
385 * Text or collapsed selection.
388 * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT )
389 * alert( 'Text is selected' );
391 CKEDITOR.SELECTION_TEXT = 2;
397 * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT )
398 * alert( 'An element is selected' );
400 CKEDITOR.SELECTION_ELEMENT = 3;
403 * Manipulates the selection in a DOM document.
407 CKEDITOR.dom.selection = function( document )
409 var lockedSelection = document.getCustomData( 'cke_locked_selection' );
411 if ( lockedSelection )
412 return lockedSelection;
414 this.document = document;
422 * IE BUG: The selection's document may be a different document than the
423 * editor document. Return null if that's the case.
425 if ( CKEDITOR.env.ie )
427 var range = this.getNative().createRange();
429 || ( range.item && range.item(0).ownerDocument != this.document.$ )
430 || ( range.parentElement && range.parentElement().ownerDocument != this.document.$ ) )
432 this.isInvalid = true;
439 var styleObjectElements =
441 img:1,hr:1,li:1,table:1,tr:1,td:1,th:1,embed:1,object:1,ol:1,ul:1,
442 a:1, input:1, form:1, select:1, textarea:1, button:1, fieldset:1, th:1, thead:1, tfoot:1
445 CKEDITOR.dom.selection.prototype =
448 * Gets the native selection object from the browser.
450 * @returns {Object} The native selection object.
452 * var selection = editor.getSelection().<b>getNative()</b>;
458 return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.$.selection );
463 return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.getWindow().$.getSelection() );
467 * Gets the type of the current selection. The following values are
470 * <li>{@link CKEDITOR.SELECTION_NONE} (1): No selection.</li>
471 * <li>{@link CKEDITOR.SELECTION_TEXT} (2): Text is selected or
472 * collapsed selection.</li>
473 * <li>{@link CKEDITOR.SELECTION_ELEMENT} (3): A element
477 * @returns {Number} One of the following constant values:
478 * {@link CKEDITOR.SELECTION_NONE}, {@link CKEDITOR.SELECTION_TEXT} or
479 * {@link CKEDITOR.SELECTION_ELEMENT}.
481 * if ( editor.getSelection().<b>getType()</b> == CKEDITOR.SELECTION_TEXT )
482 * alert( 'Text is selected' );
488 var cache = this._.cache;
492 var type = CKEDITOR.SELECTION_NONE;
496 var sel = this.getNative(),
499 if ( ieType == 'Text' )
500 type = CKEDITOR.SELECTION_TEXT;
502 if ( ieType == 'Control' )
503 type = CKEDITOR.SELECTION_ELEMENT;
505 // It is possible that we can still get a text range
506 // object even when type == 'None' is returned by IE.
507 // So we'd better check the object returned by
508 // createRange() rather than by looking at the type.
509 if ( sel.createRange().parentElement )
510 type = CKEDITOR.SELECTION_TEXT;
514 return ( cache.type = type );
519 var cache = this._.cache;
523 var type = CKEDITOR.SELECTION_TEXT;
525 var sel = this.getNative();
528 type = CKEDITOR.SELECTION_NONE;
529 else if ( sel.rangeCount == 1 )
531 // Check if the actual selection is a control (IMG,
532 // TABLE, HR, etc...).
534 var range = sel.getRangeAt(0),
535 startContainer = range.startContainer;
537 if ( startContainer == range.endContainer
538 && startContainer.nodeType == 1
539 && ( range.endOffset - range.startOffset ) == 1
540 && styleObjectElements[ startContainer.childNodes[ range.startOffset ].nodeName.toLowerCase() ] )
542 type = CKEDITOR.SELECTION_ELEMENT;
546 return ( cache.type = type );
550 * Retrieve the {@link CKEDITOR.dom.range} instances that represent the current selection.
551 * Note: Some browsers returns multiple ranges even on a sequent selection, e.g. Firefox returns
552 * one range for each table cell when one or more table row is selected.
555 * var ranges = selection.getRanges();
556 * alert(ranges.length);
558 getRanges : (function()
560 var func = CKEDITOR.env.ie ?
563 function getNodeIndex( node ) { return new CKEDITOR.dom.node( node ).getIndex(); }
565 // Finds the container and offset for a specific boundary
567 var getBoundaryInformation = function( range, start )
569 // Creates a collapsed range at the requested boundary.
570 range = range.duplicate();
571 range.collapse( start );
573 // Gets the element that encloses the range entirely.
574 var parent = range.parentElement();
576 // Empty parent element, e.g. <i>^</i>
577 if ( !parent.hasChildNodes() )
578 return { container : parent, offset : 0 };
580 var siblings = parent.children,
582 testRange = range.duplicate(),
584 endIndex = siblings.length - 1,
589 // Binary search over all element childs to test the range to see whether
590 // range is right on the boundary of one element.
591 while ( startIndex <= endIndex )
593 index = Math.floor( ( startIndex + endIndex ) / 2 );
594 child = siblings[ index ];
595 testRange.moveToElementText( child );
596 position = testRange.compareEndPoints( 'StartToStart', range );
599 endIndex = index - 1;
600 else if ( position < 0 )
601 startIndex = index + 1;
603 return { container : parent, offset : getNodeIndex( child ) };
606 // All childs are text nodes,
607 // or to the right hand of test range are all text nodes. (#6992)
608 if ( index == -1 || index == siblings.length - 1 && position < 0 )
610 // Adapt test range to embrace the entire parent contents.
611 testRange.moveToElementText( parent );
612 testRange.setEndPoint( 'StartToStart', range );
614 // IE report line break as CRLF with range.text but
615 // only LF with textnode.nodeValue, normalize them to avoid
616 // breaking character counting logic below. (#3949)
617 distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
619 siblings = parent.childNodes;
621 // Actual range anchor right beside test range at the boundary of text node.
624 child = siblings[ siblings.length - 1 ];
626 if ( child.nodeType == CKEDITOR.NODE_ELEMENT )
627 return { container : parent, offset : siblings.length };
629 return { container : child, offset : child.nodeValue.length };
632 // Start the measuring until distance overflows, meanwhile count the text nodes.
633 var i = siblings.length;
634 while ( distance > 0 )
635 distance -= siblings[ --i ].nodeValue.length;
637 return { container : siblings[ i ], offset : -distance };
639 // Test range was one offset beyond OR behind the anchored text node.
642 // Adapt one side of test range to the actual range
643 // for measuring the offset between them.
644 testRange.collapse( position > 0 ? true : false );
645 testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
647 // IE report line break as CRLF with range.text but
648 // only LF with textnode.nodeValue, normalize them to avoid
649 // breaking character counting logic below. (#3949)
650 distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
652 // Actual range anchor right beside test range at the inner boundary of text node.
654 return { container : parent, offset : getNodeIndex( child ) + ( position > 0 ? 0 : 1 ) };
656 // Start the measuring until distance overflows, meanwhile count the text nodes.
657 while ( distance > 0 )
659 child = child[ position > 0 ? 'previousSibling' : 'nextSibling' ];
662 distance -= child.nodeValue.length;
664 // Measurement in IE could be somtimes wrong because of <select> element. (#4611)
667 return { container : parent, offset : getNodeIndex( child ) };
671 return { container : child, offset : position > 0 ? -distance : child.nodeValue.length + distance };
677 // IE doesn't have range support (in the W3C way), so we
678 // need to do some magic to transform selections into
679 // CKEDITOR.dom.range instances.
681 var sel = this.getNative(),
682 nativeRange = sel && sel.createRange(),
683 type = this.getType(),
689 if ( type == CKEDITOR.SELECTION_TEXT )
691 range = new CKEDITOR.dom.range( this.document );
693 var boundaryInfo = getBoundaryInformation( nativeRange, true );
694 range.setStart( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );
696 boundaryInfo = getBoundaryInformation( nativeRange );
697 range.setEnd( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );
699 // Correct an invalid IE range case on empty list item. (#5850)
700 if ( range.endContainer.getPosition( range.startContainer ) & CKEDITOR.POSITION_PRECEDING
701 && range.endOffset <= range.startContainer.getIndex() )
708 else if ( type == CKEDITOR.SELECTION_ELEMENT )
712 for ( var i = 0 ; i < nativeRange.length ; i++ )
714 var element = nativeRange.item( i ),
715 parentElement = element.parentNode,
718 range = new CKEDITOR.dom.range( this.document );
720 for (; j < parentElement.childNodes.length && parentElement.childNodes[j] != element ; j++ )
723 range.setStart( new CKEDITOR.dom.node( parentElement ), j );
724 range.setEnd( new CKEDITOR.dom.node( parentElement ), j + 1 );
725 retval.push( range );
738 // On browsers implementing the W3C range, we simply
739 // tranform the native ranges in CKEDITOR.dom.range
745 sel = this.getNative();
750 // On WebKit, it may happen that we'll have no selection
751 // available. We normalize it here by replicating the
752 // behavior of other browsers.
753 if ( !sel.rangeCount )
755 range = new CKEDITOR.dom.range( doc );
756 range.moveToElementEditStart( doc.getBody() );
757 ranges.push( range );
760 for ( var i = 0 ; i < sel.rangeCount ; i++ )
762 var nativeRange = sel.getRangeAt( i );
764 range = new CKEDITOR.dom.range( doc );
766 range.setStart( new CKEDITOR.dom.node( nativeRange.startContainer ), nativeRange.startOffset );
767 range.setEnd( new CKEDITOR.dom.node( nativeRange.endContainer ), nativeRange.endOffset );
768 ranges.push( range );
773 return function( onlyEditables )
775 var cache = this._.cache;
776 if ( cache.ranges && !onlyEditables )
778 else if ( !cache.ranges )
779 cache.ranges = new CKEDITOR.dom.rangeList( func.call( this ) );
781 // Split range into multiple by read-only nodes.
784 var ranges = cache.ranges;
785 for ( var i = 0; i < ranges.length; i++ )
787 var range = ranges[ i ];
789 // Drop range spans inside one ready-only node.
790 var parent = range.getCommonAncestor();
791 if ( parent.isReadOnly() )
792 ranges.splice( i, 1 );
794 if ( range.collapsed )
797 var startContainer = range.startContainer,
798 endContainer = range.endContainer,
799 startOffset = range.startOffset,
800 endOffset = range.endOffset,
801 walkerRange = range.clone();
803 // Range may start inside a non-editable element, restart range
806 if ( ( readOnly = startContainer.isReadOnly() ) )
807 range.setStartAfter( readOnly );
809 // Enlarge range start/end with text node to avoid walker
810 // being DOM destructive, it doesn't interfere our checking
811 // of elements below as well.
812 if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
814 if ( startOffset >= startContainer.getLength() )
815 walkerRange.setStartAfter( startContainer );
817 walkerRange.setStartBefore( startContainer );
820 if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
823 walkerRange.setEndBefore( endContainer );
825 walkerRange.setEndAfter( endContainer );
828 // Looking for non-editable element inside the range.
829 var walker = new CKEDITOR.dom.walker( walkerRange );
830 walker.evaluator = function( node )
832 if ( node.type == CKEDITOR.NODE_ELEMENT
833 && node.isReadOnly() )
835 var newRange = range.clone();
836 range.setEndBefore( node );
838 // Drop collapsed range around read-only elements,
839 // it make sure the range list empty when selecting
840 // only non-editable elements.
841 if ( range.collapsed )
842 ranges.splice( i--, 1 );
844 // Avoid creating invalid range.
845 if ( !( node.getPosition( walkerRange.endContainer ) & CKEDITOR.POSITION_CONTAINS ) )
847 newRange.setStartAfter( node );
848 if ( !newRange.collapsed )
849 ranges.splice( i + 1, 0, newRange );
867 * Gets the DOM element in which the selection starts.
868 * @returns {CKEDITOR.dom.element} The element at the beginning of the
871 * var element = editor.getSelection().<b>getStartElement()</b>;
872 * alert( element.getName() );
874 getStartElement : function()
876 var cache = this._.cache;
877 if ( cache.startElement !== undefined )
878 return cache.startElement;
881 sel = this.getNative();
883 switch ( this.getType() )
885 case CKEDITOR.SELECTION_ELEMENT :
886 return this.getSelectedElement();
888 case CKEDITOR.SELECTION_TEXT :
890 var range = this.getRanges()[0];
894 if ( !range.collapsed )
898 // Decrease the range content to exclude particial
899 // selected node on the start which doesn't have
900 // visual impact. ( #3231 )
903 var startContainer = range.startContainer,
904 startOffset = range.startOffset;
905 // Limit the fix only to non-block elements.(#3950)
906 if ( startOffset == ( startContainer.getChildCount ?
907 startContainer.getChildCount() : startContainer.getLength() )
908 && !startContainer.isBlockBoundary() )
909 range.setStartAfter( startContainer );
913 node = range.startContainer;
915 if ( node.type != CKEDITOR.NODE_ELEMENT )
916 return node.getParent();
918 node = node.getChild( range.startOffset );
920 if ( !node || node.type != CKEDITOR.NODE_ELEMENT )
921 node = range.startContainer;
924 var child = node.getFirst();
925 while ( child && child.type == CKEDITOR.NODE_ELEMENT )
928 child = child.getFirst();
934 node = range.startContainer;
935 if ( node.type != CKEDITOR.NODE_ELEMENT )
936 node = node.getParent();
943 return cache.startElement = ( node ? new CKEDITOR.dom.element( node ) : null );
947 * Gets the current selected element.
948 * @returns {CKEDITOR.dom.element} The selected element. Null if no
949 * selection is available or the selection type is not
950 * {@link CKEDITOR.SELECTION_ELEMENT}.
952 * var element = editor.getSelection().<b>getSelectedElement()</b>;
953 * alert( element.getName() );
955 getSelectedElement : function()
957 var cache = this._.cache;
958 if ( cache.selectedElement !== undefined )
959 return cache.selectedElement;
963 var node = CKEDITOR.tools.tryThese(
964 // Is it native IE control type selection?
967 return self.getNative().createRange().item( 0 );
969 // Figure it out by checking if there's a single enclosed
970 // node of the range.
973 var range = self.getRanges()[ 0 ],
977 // Check first any enclosed element, e.g. <ul>[<li><a href="#">item</a></li>]</ul>
978 for ( var i = 2; i && !( ( enclosed = range.getEnclosedNode() )
979 && ( enclosed.type == CKEDITOR.NODE_ELEMENT )
980 && styleObjectElements[ enclosed.getName() ]
981 && ( selected = enclosed ) ); i-- )
983 // Then check any deep wrapped element, e.g. [<b><i><img /></i></b>]
984 range.shrink( CKEDITOR.SHRINK_ELEMENT );
990 return cache.selectedElement = ( node ? new CKEDITOR.dom.element( node ) : null );
995 // Call all cacheable function.
997 this.getStartElement();
998 this.getSelectedElement();
1000 // The native selection is not available when locked.
1001 this._.cache.nativeSel = {};
1005 // Save this selection inside the DOM document.
1006 this.document.setCustomData( 'cke_locked_selection', this );
1009 unlock : function( restore )
1011 var doc = this.document,
1012 lockedSelection = doc.getCustomData( 'cke_locked_selection' );
1014 if ( lockedSelection )
1016 doc.setCustomData( 'cke_locked_selection', null );
1020 var selectedElement = lockedSelection.getSelectedElement(),
1021 ranges = !selectedElement && lockedSelection.getRanges();
1026 doc.getBody().focus();
1028 if ( selectedElement )
1029 this.selectElement( selectedElement );
1031 this.selectRanges( ranges );
1035 if ( !lockedSelection || !restore )
1048 * Make the current selection of type {@link CKEDITOR.SELECTION_ELEMENT} by enclosing the specified element.
1051 selectElement : function( element )
1053 if ( this.isLocked )
1055 var range = new CKEDITOR.dom.range( this.document );
1056 range.setStartBefore( element );
1057 range.setEndAfter( element );
1059 this._.cache.selectedElement = element;
1060 this._.cache.startElement = element;
1061 this._.cache.ranges = new CKEDITOR.dom.rangeList( range );
1062 this._.cache.type = CKEDITOR.SELECTION_ELEMENT;
1067 if ( CKEDITOR.env.ie )
1069 this.getNative().empty();
1073 // Try to select the node as a control.
1074 range = this.document.$.body.createControlRange();
1075 range.addElement( element.$ );
1080 // If failed, select it as a text range.
1081 range = this.document.$.body.createTextRange();
1082 range.moveToElementText( element.$ );
1087 this.document.fire( 'selectionchange' );
1094 // Create the range for the element.
1095 range = this.document.$.createRange();
1096 range.selectNode( element.$ );
1098 // Select the range.
1099 var sel = this.getNative();
1100 sel.removeAllRanges();
1101 sel.addRange( range );
1108 * Adding the specified ranges to document selection preceding
1109 * by clearing up the original selection.
1110 * @param {CKEDITOR.dom.range} ranges
1112 selectRanges : function( ranges )
1114 if ( this.isLocked )
1116 this._.cache.selectedElement = null;
1117 this._.cache.startElement = ranges[ 0 ] && ranges[ 0 ].getTouchedStartNode();
1118 this._.cache.ranges = new CKEDITOR.dom.rangeList( ranges );
1119 this._.cache.type = CKEDITOR.SELECTION_TEXT;
1124 if ( CKEDITOR.env.ie )
1126 if ( ranges.length > 1 )
1128 // IE doesn't accept multiple ranges selection, so we join all into one.
1129 var last = ranges[ ranges.length -1 ] ;
1130 ranges[ 0 ].setEnd( last.endContainer, last.endOffset );
1135 ranges[ 0 ].select();
1141 var sel = this.getNative();
1143 if ( ranges.length )
1144 sel.removeAllRanges();
1146 for ( var i = 0 ; i < ranges.length ; i++ )
1148 // Joining sequential ranges introduced by
1149 // readonly elements protection.
1150 if ( i < ranges.length -1 )
1152 var left = ranges[ i ], right = ranges[ i +1 ],
1153 between = left.clone();
1154 between.setStart( left.endContainer, left.endOffset );
1155 between.setEnd( right.startContainer, right.startOffset );
1157 // Don't confused by Firefox adjancent multi-ranges
1158 // introduced by table cells selection.
1159 if ( !between.collapsed )
1161 between.shrink( CKEDITOR.NODE_ELEMENT, true );
1162 var ancestor = between.getCommonAncestor(),
1163 enclosed = between.getEnclosedNode();
1165 // The following cases has to be considered:
1166 // 1. <span contenteditable="false">[placeholder]</span>
1167 // 2. <input contenteditable="false" type="radio"/> (#6621)
1168 if ( ancestor.isReadOnly() || enclosed && enclosed.isReadOnly() )
1170 right.setStart( left.startContainer, left.startOffset );
1171 ranges.splice( i--, 1 );
1177 var range = ranges[ i ];
1178 var nativeRange = this.document.$.createRange();
1179 var startContainer = range.startContainer;
1181 // In FF2, if we have a collapsed range, inside an empty
1182 // element, we must add something to it otherwise the caret
1183 // will not be visible.
1184 // In Opera instead, the selection will be moved out of the
1186 if ( range.collapsed &&
1187 ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) ) &&
1188 startContainer.type == CKEDITOR.NODE_ELEMENT &&
1189 !startContainer.getChildCount() )
1191 startContainer.appendText( '' );
1194 nativeRange.setStart( startContainer.$, range.startOffset );
1195 nativeRange.setEnd( range.endContainer.$, range.endOffset );
1197 // Select the range.
1198 sel.addRange( nativeRange );
1206 * Create bookmark for every single of this selection range (from #getRanges)
1207 * by calling the {@link CKEDITOR.dom.range.prototype.createBookmark} method,
1208 * with extra cares to avoid interferon among those ranges. Same arguments are
1209 * received as with the underlay range method.
1211 createBookmarks : function( serializable )
1213 return this.getRanges().createBookmarks( serializable );
1217 * Create bookmark for every single of this selection range (from #getRanges)
1218 * by calling the {@link CKEDITOR.dom.range.prototype.createBookmark2} method,
1219 * with extra cares to avoid interferon among those ranges. Same arguments are
1220 * received as with the underlay range method.
1222 createBookmarks2 : function( normalized )
1224 return this.getRanges().createBookmarks2( normalized );
1228 * Select the virtual ranges denote by the bookmarks by calling #selectRanges.
1231 selectBookmarks : function( bookmarks )
1234 for ( var i = 0 ; i < bookmarks.length ; i++ )
1236 var range = new CKEDITOR.dom.range( this.document );
1237 range.moveToBookmark( bookmarks[i] );
1238 ranges.push( range );
1240 this.selectRanges( ranges );
1245 * Retrieve the common ancestor node of the first range and the last range.
1247 getCommonAncestor : function()
1249 var ranges = this.getRanges(),
1250 startNode = ranges[ 0 ].startContainer,
1251 endNode = ranges[ ranges.length - 1 ].endContainer;
1252 return startNode.getCommonAncestor( endNode );
1256 * Moving scroll bar to the current selection's start position.
1258 scrollIntoView : function()
1260 // If we have split the block, adds a temporary span at the
1261 // range position and scroll relatively to it.
1262 var start = this.getStartElement();
1263 start.scrollIntoView();
1270 var notWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
1271 fillerTextRegex = /\ufeff|\u00a0/,
1272 nonCells = { table:1,tbody:1,tr:1 };
1274 CKEDITOR.dom.range.prototype.select =
1277 function( forceExpand )
1279 var collapsed = this.collapsed;
1280 var isStartMarkerAlone;
1283 // IE doesn't support selecting the entire table row/cell, move the selection into cells, e.g.
1284 // <table><tbody><tr>[<td>cell</b></td>... => <table><tbody><tr><td>[cell</td>...
1285 if ( this.startContainer.type == CKEDITOR.NODE_ELEMENT && this.startContainer.getName() in nonCells
1286 || this.endContainer.type == CKEDITOR.NODE_ELEMENT && this.endContainer.getName() in nonCells )
1288 this.shrink( CKEDITOR.NODE_ELEMENT, true );
1291 var bookmark = this.createBookmark();
1293 // Create marker tags for the start and end boundaries.
1294 var startNode = bookmark.startNode;
1298 endNode = bookmark.endNode;
1300 // Create the main range which will be used for the selection.
1301 var ieRange = this.document.$.body.createTextRange();
1303 // Position the range at the start boundary.
1304 ieRange.moveToElementText( startNode.$ );
1305 ieRange.moveStart( 'character', 1 );
1309 // Create a tool range for the end.
1310 var ieRangeEnd = this.document.$.body.createTextRange();
1312 // Position the tool range at the end.
1313 ieRangeEnd.moveToElementText( endNode.$ );
1315 // Move the end boundary of the main range to match the tool range.
1316 ieRange.setEndPoint( 'EndToEnd', ieRangeEnd );
1317 ieRange.moveEnd( 'character', -1 );
1321 // The isStartMarkerAlone logic comes from V2. It guarantees that the lines
1322 // will expand and that the cursor will be blinking on the right place.
1323 // Actually, we are using this flag just to avoid using this hack in all
1324 // situations, but just on those needed.
1325 var next = startNode.getNext( notWhitespaces );
1326 isStartMarkerAlone = ( !( next && next.getText && next.getText().match( fillerTextRegex ) ) // already a filler there?
1327 && ( forceExpand || !startNode.hasPrevious() || ( startNode.getPrevious().is && startNode.getPrevious().is( 'br' ) ) ) );
1329 // Append a temporary <span></span> before the selection.
1330 // This is needed to avoid IE destroying selections inside empty
1331 // inline elements, like <b></b> (#253).
1332 // It is also needed when placing the selection right after an inline
1333 // element to avoid the selection moving inside of it.
1334 dummySpan = this.document.createElement( 'span' );
1335 dummySpan.setHtml( '' ); // Zero Width No-Break Space (U+FEFF). See #1359.
1336 dummySpan.insertBefore( startNode );
1338 if ( isStartMarkerAlone )
1340 // To expand empty blocks or line spaces after <br>, we need
1341 // instead to have any char, which will be later deleted using the
1343 // \ufeff = Zero Width No-Break Space (U+FEFF). (#1359)
1344 this.document.createText( '\ufeff' ).insertBefore( startNode );
1348 // Remove the markers (reset the position, because of the changes in the DOM tree).
1349 this.setStartBefore( startNode );
1354 if ( isStartMarkerAlone )
1356 // Move the selection start to include the temporary \ufeff.
1357 ieRange.moveStart( 'character', -1 );
1361 // Remove our temporary stuff.
1362 this.document.$.selection.clear();
1367 this.moveToPosition( dummySpan, CKEDITOR.POSITION_BEFORE_START );
1372 this.setEndBefore( endNode );
1377 this.document.fire( 'selectionchange' );
1382 var startContainer = this.startContainer;
1384 // If we have a collapsed range, inside an empty element, we must add
1385 // something to it, otherwise the caret will not be visible.
1386 if ( this.collapsed && startContainer.type == CKEDITOR.NODE_ELEMENT && !startContainer.getChildCount() )
1387 startContainer.append( new CKEDITOR.dom.text( '' ) );
1389 var nativeRange = this.document.$.createRange();
1390 nativeRange.setStart( startContainer.$, this.startOffset );
1394 nativeRange.setEnd( this.endContainer.$, this.endOffset );
1398 // There is a bug in Firefox implementation (it would be too easy
1399 // otherwise). The new start can't be after the end (W3C says it can).
1400 // So, let's create a new range and collapse it to the desired point.
1401 if ( e.toString().indexOf( 'NS_ERROR_ILLEGAL_VALUE' ) >= 0 )
1403 this.collapse( true );
1404 nativeRange.setEnd( this.endContainer.$, this.endOffset );
1410 var selection = this.document.getSelection().getNative();
1411 // getSelection() returns null in case when iframe is "display:none" in FF. (#6577)
1414 selection.removeAllRanges();
1415 selection.addRange( nativeRange );