JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
85981fa078aff2329c200fd4da6770bdf3f1811a
[ckeditor.git] / _source / plugins / selection / plugin.js
1 /*\r
2 Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 (function()\r
7 {\r
8         // #### checkSelectionChange : START\r
9 \r
10         // The selection change check basically saves the element parent tree of\r
11         // the current node and check it on successive requests. If there is any\r
12         // change on the tree, then the selectionChange event gets fired.\r
13         function checkSelectionChange()\r
14         {\r
15                 try\r
16                 {\r
17                         // In IE, the "selectionchange" event may still get thrown when\r
18                         // releasing the WYSIWYG mode, so we need to check it first.\r
19                         var sel = this.getSelection();\r
20                         if ( !sel )\r
21                                 return;\r
22 \r
23                         var firstElement = sel.getStartElement();\r
24                         var currentPath = new CKEDITOR.dom.elementPath( firstElement );\r
25 \r
26                         if ( !currentPath.compare( this._.selectionPreviousPath ) )\r
27                         {\r
28                                 this._.selectionPreviousPath = currentPath;\r
29                                 this.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );\r
30                         }\r
31                 }\r
32                 catch (e)\r
33                 {}\r
34         }\r
35 \r
36         var checkSelectionChangeTimer,\r
37                 checkSelectionChangeTimeoutPending;\r
38 \r
39         function checkSelectionChangeTimeout()\r
40         {\r
41                 // Firing the "OnSelectionChange" event on every key press started to\r
42                 // be too slow. This function guarantees that there will be at least\r
43                 // 200ms delay between selection checks.\r
44 \r
45                 checkSelectionChangeTimeoutPending = true;\r
46 \r
47                 if ( checkSelectionChangeTimer )\r
48                         return;\r
49 \r
50                 checkSelectionChangeTimeoutExec.call( this );\r
51 \r
52                 checkSelectionChangeTimer = CKEDITOR.tools.setTimeout( checkSelectionChangeTimeoutExec, 200, this );\r
53         }\r
54 \r
55         function checkSelectionChangeTimeoutExec()\r
56         {\r
57                 checkSelectionChangeTimer = null;\r
58 \r
59                 if ( checkSelectionChangeTimeoutPending )\r
60                 {\r
61                         // Call this with a timeout so the browser properly moves the\r
62                         // selection after the mouseup. It happened that the selection was\r
63                         // being moved after the mouseup when clicking inside selected text\r
64                         // with Firefox.\r
65                         CKEDITOR.tools.setTimeout( checkSelectionChange, 0, this );\r
66 \r
67                         checkSelectionChangeTimeoutPending = false;\r
68                 }\r
69         }\r
70 \r
71         // #### checkSelectionChange : END\r
72 \r
73         var selectAllCmd =\r
74         {\r
75                 exec : function( editor )\r
76                 {\r
77                         switch ( editor.mode )\r
78                         {\r
79                                 case 'wysiwyg' :\r
80                                         editor.document.$.execCommand( 'SelectAll', false, null );\r
81                                         break;\r
82                                 case 'source' :\r
83                                         // TODO\r
84                         }\r
85                 },\r
86                 canUndo : false\r
87         };\r
88 \r
89         CKEDITOR.plugins.add( 'selection',\r
90         {\r
91                 init : function( editor )\r
92                 {\r
93                         editor.on( 'contentDom', function()\r
94                                 {\r
95                                         var doc = editor.document,\r
96                                                 body = doc.getBody();\r
97 \r
98                                         if ( CKEDITOR.env.ie )\r
99                                         {\r
100                                                 // Other browsers don't loose the selection if the\r
101                                                 // editor document loose the focus. In IE, we don't\r
102                                                 // have support for it, so we reproduce it here, other\r
103                                                 // than firing the selection change event.\r
104 \r
105                                                 var savedRange,\r
106                                                         saveEnabled;\r
107 \r
108                                                 // "onfocusin" is fired before "onfocus". It makes it\r
109                                                 // possible to restore the selection before click\r
110                                                 // events get executed.\r
111                                                 body.on( 'focusin', function()\r
112                                                         {\r
113                                                                 // If we have saved a range, restore it at this\r
114                                                                 // point.\r
115                                                                 if ( savedRange )\r
116                                                                 {\r
117                                                                         // Well not break because of this.\r
118                                                                         try\r
119                                                                         {\r
120                                                                                 savedRange.select();\r
121                                                                         }\r
122                                                                         catch (e)\r
123                                                                         {}\r
124 \r
125                                                                         savedRange = null;\r
126                                                                 }\r
127                                                         });\r
128 \r
129                                                 editor.window.on( 'focus', function()\r
130                                                         {\r
131                                                                 // Enable selections to be saved.\r
132                                                                 saveEnabled = true;\r
133 \r
134                                                                 saveSelection();\r
135                                                         });\r
136 \r
137                                                 body.on( 'beforedeactivate', function()\r
138                                                         {\r
139                                                                 // Disable selections from being saved.\r
140                                                                 saveEnabled = false;\r
141                                                         });\r
142 \r
143                                                 // IE fires the "selectionchange" event when clicking\r
144                                                 // inside a selection. We don't want to capture that.\r
145                                                 body.on( 'mousedown', disableSave );\r
146                                                 body.on( 'mouseup',\r
147                                                         function()\r
148                                                         {\r
149                                                                 saveEnabled = true;\r
150                                                                 setTimeout( function()\r
151                                                                         {\r
152                                                                                 saveSelection( true );\r
153                                                                         },\r
154                                                                         0 );\r
155                                                         });\r
156 \r
157                                                 body.on( 'keydown', disableSave );\r
158                                                 body.on( 'keyup',\r
159                                                         function()\r
160                                                         {\r
161                                                                 saveEnabled = true;\r
162                                                                 saveSelection();\r
163                                                         });\r
164 \r
165 \r
166                                                 // IE is the only to provide the "selectionchange"\r
167                                                 // event.\r
168                                                 doc.on( 'selectionchange', saveSelection );\r
169 \r
170                                                 function disableSave()\r
171                                                 {\r
172                                                         saveEnabled = false;\r
173                                                 }\r
174 \r
175                                                 function saveSelection( testIt )\r
176                                                 {\r
177                                                         if ( saveEnabled )\r
178                                                         {\r
179                                                                 var doc = editor.document,\r
180                                                                         sel = doc && doc.$.selection;\r
181 \r
182                                                                 // There is a very specific case, when clicking\r
183                                                                 // inside a text selection. In that case, the\r
184                                                                 // selection collapses at the clicking point,\r
185                                                                 // but the selection object remains in an\r
186                                                                 // unknown state, making createRange return a\r
187                                                                 // range at the very start of the document. In\r
188                                                                 // such situation we have to test the range, to\r
189                                                                 // be sure it's valid.\r
190                                                                 if ( testIt && sel && sel.type == 'None' )\r
191                                                                 {\r
192                                                                         // The "InsertImage" command can be used to\r
193                                                                         // test whether the selection is good or not.\r
194                                                                         // If not, it's enough to give some time to\r
195                                                                         // IE to put things in order for us.\r
196                                                                         if ( !doc.$.queryCommandEnabled( 'InsertImage' ) )\r
197                                                                         {\r
198                                                                                 CKEDITOR.tools.setTimeout( saveSelection, 50, this, true );\r
199                                                                                 return;\r
200                                                                         }\r
201                                                                 }\r
202 \r
203                                                                 savedRange = sel && sel.createRange();\r
204 \r
205                                                                 checkSelectionChangeTimeout.call( editor );\r
206                                                         }\r
207                                                 }\r
208                                         }\r
209                                         else\r
210                                         {\r
211                                                 // In other browsers, we make the selection change\r
212                                                 // check based on other events, like clicks or keys\r
213                                                 // press.\r
214 \r
215                                                 doc.on( 'mouseup', checkSelectionChangeTimeout, editor );\r
216                                                 doc.on( 'keyup', checkSelectionChangeTimeout, editor );\r
217                                         }\r
218                                 });\r
219 \r
220                         editor.addCommand( 'selectAll', selectAllCmd );\r
221                         editor.ui.addButton( 'SelectAll',\r
222                                 {\r
223                                         label : editor.lang.selectAll,\r
224                                         command : 'selectAll'\r
225                                 });\r
226 \r
227                         editor.selectionChange = checkSelectionChangeTimeout;\r
228                 }\r
229         });\r
230 \r
231         /**\r
232          * Gets the current selection from the editing area when in WYSIWYG mode.\r
233          * @returns {CKEDITOR.dom.selection} A selection object or null if not on\r
234          *              WYSIWYG mode or no selection is available.\r
235          * @example\r
236          * var selection = CKEDITOR.instances.editor1.<b>getSelection()</b>;\r
237          * alert( selection.getType() );\r
238          */\r
239         CKEDITOR.editor.prototype.getSelection = function()\r
240         {\r
241                 return this.document && this.document.getSelection();\r
242         };\r
243 \r
244         CKEDITOR.editor.prototype.forceNextSelectionCheck = function()\r
245         {\r
246                 delete this._.selectionPreviousPath;\r
247         };\r
248 \r
249         /**\r
250          * Gets the current selection from the document.\r
251          * @returns {CKEDITOR.dom.selection} A selection object.\r
252          * @example\r
253          * var selection = CKEDITOR.instances.editor1.document.<b>getSelection()</b>;\r
254          * alert( selection.getType() );\r
255          */\r
256         CKEDITOR.dom.document.prototype.getSelection = function()\r
257         {\r
258                 var sel = new CKEDITOR.dom.selection( this );\r
259                 return ( !sel || sel.isInvalid ) ? null : sel;\r
260         };\r
261 \r
262         /**\r
263          * No selection.\r
264          * @constant\r
265          * @example\r
266          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_NONE )\r
267          *     alert( 'Nothing is selected' );\r
268          */\r
269         CKEDITOR.SELECTION_NONE         = 1;\r
270 \r
271         /**\r
272          * Text or collapsed selection.\r
273          * @constant\r
274          * @example\r
275          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT )\r
276          *     alert( 'Text is selected' );\r
277          */\r
278         CKEDITOR.SELECTION_TEXT         = 2;\r
279 \r
280         /**\r
281          * Element selection.\r
282          * @constant\r
283          * @example\r
284          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT )\r
285          *     alert( 'An element is selected' );\r
286          */\r
287         CKEDITOR.SELECTION_ELEMENT      = 3;\r
288 \r
289         /**\r
290          * Manipulates the selection in a DOM document.\r
291          * @constructor\r
292          * @example\r
293          */\r
294         CKEDITOR.dom.selection = function( document )\r
295         {\r
296                 var lockedSelection = document.getCustomData( 'cke_locked_selection' );\r
297 \r
298                 if ( lockedSelection )\r
299                         return lockedSelection;\r
300 \r
301                 this.document = document;\r
302                 this.isLocked = false;\r
303                 this._ =\r
304                 {\r
305                         cache : {}\r
306                 };\r
307 \r
308                 /**\r
309                  * IE BUG: The selection's document may be a different document than the\r
310                  * editor document. Return null if that's the case.\r
311                  */\r
312                 if ( CKEDITOR.env.ie )\r
313                 {\r
314                         var range = this.getNative().createRange();\r
315                         if ( !range\r
316                                 || ( range.item && range.item(0).ownerDocument != this.document.$ )\r
317                                 || ( range.parentElement && range.parentElement().ownerDocument != this.document.$ ) )\r
318                         {\r
319                                 this.isInvalid = true;\r
320                         }\r
321                 }\r
322 \r
323                 return this;\r
324         };\r
325 \r
326         var styleObjectElements =\r
327         {\r
328                 img:1,hr:1,li:1,table:1,tr:1,td:1,th:1,embed:1,object:1,ol:1,ul:1,\r
329                 a:1, input:1, form:1, select:1, textarea:1, button:1, fieldset:1, th:1, thead:1, tfoot:1\r
330         };\r
331 \r
332         CKEDITOR.dom.selection.prototype =\r
333         {\r
334                 /**\r
335                  * Gets the native selection object from the browser.\r
336                  * @function\r
337                  * @returns {Object} The native selection object.\r
338                  * @example\r
339                  * var selection = editor.getSelection().<b>getNative()</b>;\r
340                  */\r
341                 getNative :\r
342                         CKEDITOR.env.ie ?\r
343                                 function()\r
344                                 {\r
345                                         return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.$.selection );\r
346                                 }\r
347                         :\r
348                                 function()\r
349                                 {\r
350                                         return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.getWindow().$.getSelection() );\r
351                                 },\r
352 \r
353                 /**\r
354                  * Gets the type of the current selection. The following values are\r
355                  * available:\r
356                  * <ul>\r
357                  *              <li>{@link CKEDITOR.SELECTION_NONE} (1): No selection.</li>\r
358                  *              <li>{@link CKEDITOR.SELECTION_TEXT} (2): Text is selected or\r
359                  *                      collapsed selection.</li>\r
360                  *              <li>{@link CKEDITOR.SELECTION_ELEMENT} (3): A element\r
361                  *                      selection.</li>\r
362                  * </ul>\r
363                  * @function\r
364                  * @returns {Number} One of the following constant values:\r
365                  *              {@link CKEDITOR.SELECTION_NONE}, {@link CKEDITOR.SELECTION_TEXT} or\r
366                  *              {@link CKEDITOR.SELECTION_ELEMENT}.\r
367                  * @example\r
368                  * if ( editor.getSelection().<b>getType()</b> == CKEDITOR.SELECTION_TEXT )\r
369                  *     alert( 'Text is selected' );\r
370                  */\r
371                 getType :\r
372                         CKEDITOR.env.ie ?\r
373                                 function()\r
374                                 {\r
375                                         var cache = this._.cache;\r
376                                         if ( cache.type )\r
377                                                 return cache.type;\r
378 \r
379                                         var type = CKEDITOR.SELECTION_NONE;\r
380 \r
381                                         try\r
382                                         {\r
383                                                 var sel = this.getNative(),\r
384                                                         ieType = sel.type;\r
385 \r
386                                                 if ( ieType == 'Text' )\r
387                                                         type = CKEDITOR.SELECTION_TEXT;\r
388 \r
389                                                 if ( ieType == 'Control' )\r
390                                                         type = CKEDITOR.SELECTION_ELEMENT;\r
391 \r
392                                                 // It is possible that we can still get a text range\r
393                                                 // object even when type == 'None' is returned by IE.\r
394                                                 // So we'd better check the object returned by\r
395                                                 // createRange() rather than by looking at the type.\r
396                                                 if ( sel.createRange().parentElement )\r
397                                                         type = CKEDITOR.SELECTION_TEXT;\r
398                                         }\r
399                                         catch(e) {}\r
400 \r
401                                         return ( cache.type = type );\r
402                                 }\r
403                         :\r
404                                 function()\r
405                                 {\r
406                                         var cache = this._.cache;\r
407                                         if ( cache.type )\r
408                                                 return cache.type;\r
409 \r
410                                         var type = CKEDITOR.SELECTION_TEXT;\r
411 \r
412                                         var sel = this.getNative();\r
413 \r
414                                         if ( !sel )\r
415                                                 type = CKEDITOR.SELECTION_NONE;\r
416                                         else if ( sel.rangeCount == 1 )\r
417                                         {\r
418                                                 // Check if the actual selection is a control (IMG,\r
419                                                 // TABLE, HR, etc...).\r
420 \r
421                                                 var range = sel.getRangeAt(0),\r
422                                                         startContainer = range.startContainer;\r
423 \r
424                                                 if ( startContainer == range.endContainer\r
425                                                         && startContainer.nodeType == 1\r
426                                                         && ( range.endOffset - range.startOffset ) == 1\r
427                                                         && styleObjectElements[ startContainer.childNodes[ range.startOffset ].nodeName.toLowerCase() ] )\r
428                                                 {\r
429                                                         type = CKEDITOR.SELECTION_ELEMENT;\r
430                                                 }\r
431                                         }\r
432 \r
433                                         return ( cache.type = type );\r
434                                 },\r
435 \r
436                 getRanges :\r
437                         CKEDITOR.env.ie ?\r
438                                 ( function()\r
439                                 {\r
440                                         // Finds the container and offset for a specific boundary\r
441                                         // of an IE range.\r
442                                         var getBoundaryInformation = function( range, start )\r
443                                         {\r
444                                                 // Creates a collapsed range at the requested boundary.\r
445                                                 range = range.duplicate();\r
446                                                 range.collapse( start );\r
447 \r
448                                                 // Gets the element that encloses the range entirely.\r
449                                                 var parent = range.parentElement();\r
450                                                 var siblings = parent.childNodes;\r
451 \r
452                                                 var testRange;\r
453 \r
454                                                 for ( var i = 0 ; i < siblings.length ; i++ )\r
455                                                 {\r
456                                                         var child = siblings[ i ];\r
457                                                         if ( child.nodeType == 1 )\r
458                                                         {\r
459                                                                 testRange = range.duplicate();\r
460 \r
461                                                                 testRange.moveToElementText( child );\r
462 \r
463                                                                 var comparisonStart = testRange.compareEndPoints( 'StartToStart', range ),\r
464                                                                         comparisonEnd = testRange.compareEndPoints( 'EndToStart', range );\r
465 \r
466                                                                 testRange.collapse();\r
467 \r
468                                                                 if ( comparisonStart > 0 )\r
469                                                                         break;\r
470                                                                 // When selection stay at the side of certain self-closing elements, e.g. BR,\r
471                                                                 // our comparison will never shows an equality. (#4824)\r
472                                                                 else if ( !comparisonStart\r
473                                                                         || comparisonEnd == 1 && comparisonStart == -1 )\r
474                                                                         return { container : parent, offset : i };\r
475                                                                 else if ( !comparisonEnd )\r
476                                                                         return { container : parent, offset : i + 1 };\r
477 \r
478                                                                 testRange = null;\r
479                                                         }\r
480                                                 }\r
481 \r
482                                                 if ( !testRange )\r
483                                                 {\r
484                                                         testRange = range.duplicate();\r
485                                                         testRange.moveToElementText( parent );\r
486                                                         testRange.collapse( false );\r
487                                                 }\r
488 \r
489                                                 testRange.setEndPoint( 'StartToStart', range );\r
490                                                 // IE report line break as CRLF with range.text but\r
491                                                 // only LF with textnode.nodeValue, normalize them to avoid\r
492                                                 // breaking character counting logic below. (#3949)\r
493                                                 var distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;\r
494 \r
495                                                 try\r
496                                                 {\r
497                                                         while ( distance > 0 )\r
498                                                                 distance -= siblings[ --i ].nodeValue.length;\r
499                                                 }\r
500                                                 // Measurement in IE could be somtimes wrong because of <select> element. (#4611)\r
501                                                 catch( e )\r
502                                                 {\r
503                                                         distance = 0;\r
504                                                 }\r
505 \r
506 \r
507                                                 if ( distance === 0 )\r
508                                                 {\r
509                                                         return {\r
510                                                                 container : parent,\r
511                                                                 offset : i\r
512                                                         };\r
513                                                 }\r
514                                                 else\r
515                                                 {\r
516                                                         return {\r
517                                                                 container : siblings[ i ],\r
518                                                                 offset : -distance\r
519                                                         };\r
520                                                 }\r
521                                         };\r
522 \r
523                                         return function()\r
524                                         {\r
525                                                 var cache = this._.cache;\r
526                                                 if ( cache.ranges )\r
527                                                         return cache.ranges;\r
528 \r
529                                                 // IE doesn't have range support (in the W3C way), so we\r
530                                                 // need to do some magic to transform selections into\r
531                                                 // CKEDITOR.dom.range instances.\r
532 \r
533                                                 var sel = this.getNative(),\r
534                                                         nativeRange = sel && sel.createRange(),\r
535                                                         type = this.getType(),\r
536                                                         range;\r
537 \r
538                                                 if ( !sel )\r
539                                                         return [];\r
540 \r
541                                                 if ( type == CKEDITOR.SELECTION_TEXT )\r
542                                                 {\r
543                                                         range = new CKEDITOR.dom.range( this.document );\r
544 \r
545                                                         var boundaryInfo = getBoundaryInformation( nativeRange, true );\r
546                                                         range.setStart( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );\r
547 \r
548                                                         boundaryInfo = getBoundaryInformation( nativeRange );\r
549                                                         range.setEnd( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );\r
550 \r
551                                                         return ( cache.ranges = [ range ] );\r
552                                                 }\r
553                                                 else if ( type == CKEDITOR.SELECTION_ELEMENT )\r
554                                                 {\r
555                                                         var retval = this._.cache.ranges = [];\r
556 \r
557                                                         for ( var i = 0 ; i < nativeRange.length ; i++ )\r
558                                                         {\r
559                                                                 var element = nativeRange.item( i ),\r
560                                                                         parentElement = element.parentNode,\r
561                                                                         j = 0;\r
562 \r
563                                                                 range = new CKEDITOR.dom.range( this.document );\r
564 \r
565                                                                 for (; j < parentElement.childNodes.length && parentElement.childNodes[j] != element ; j++ )\r
566                                                                 { /*jsl:pass*/ }\r
567 \r
568                                                                 range.setStart( new CKEDITOR.dom.node( parentElement ), j );\r
569                                                                 range.setEnd( new CKEDITOR.dom.node( parentElement ), j + 1 );\r
570                                                                 retval.push( range );\r
571                                                         }\r
572 \r
573                                                         return retval;\r
574                                                 }\r
575 \r
576                                                 return ( cache.ranges = [] );\r
577                                         };\r
578                                 })()\r
579                         :\r
580                                 function()\r
581                                 {\r
582                                         var cache = this._.cache;\r
583                                         if ( cache.ranges )\r
584                                                 return cache.ranges;\r
585 \r
586                                         // On browsers implementing the W3C range, we simply\r
587                                         // tranform the native ranges in CKEDITOR.dom.range\r
588                                         // instances.\r
589 \r
590                                         var ranges = [];\r
591                                         var sel = this.getNative();\r
592 \r
593                                         if ( !sel )\r
594                                                 return [];\r
595 \r
596                                         for ( var i = 0 ; i < sel.rangeCount ; i++ )\r
597                                         {\r
598                                                 var nativeRange = sel.getRangeAt( i );\r
599                                                 var range = new CKEDITOR.dom.range( this.document );\r
600 \r
601                                                 range.setStart( new CKEDITOR.dom.node( nativeRange.startContainer ), nativeRange.startOffset );\r
602                                                 range.setEnd( new CKEDITOR.dom.node( nativeRange.endContainer ), nativeRange.endOffset );\r
603                                                 ranges.push( range );\r
604                                         }\r
605 \r
606                                         return ( cache.ranges = ranges );\r
607                                 },\r
608 \r
609                 /**\r
610                  * Gets the DOM element in which the selection starts.\r
611                  * @returns {CKEDITOR.dom.element} The element at the beginning of the\r
612                  *              selection.\r
613                  * @example\r
614                  * var element = editor.getSelection().<b>getStartElement()</b>;\r
615                  * alert( element.getName() );\r
616                  */\r
617                 getStartElement : function()\r
618                 {\r
619                         var cache = this._.cache;\r
620                         if ( cache.startElement !== undefined )\r
621                                 return cache.startElement;\r
622 \r
623                         var node,\r
624                                 sel = this.getNative();\r
625 \r
626                         switch ( this.getType() )\r
627                         {\r
628                                 case CKEDITOR.SELECTION_ELEMENT :\r
629                                         return this.getSelectedElement();\r
630 \r
631                                 case CKEDITOR.SELECTION_TEXT :\r
632 \r
633                                         var range = this.getRanges()[0];\r
634 \r
635                                         if ( range )\r
636                                         {\r
637                                                 if ( !range.collapsed )\r
638                                                 {\r
639                                                         range.optimize();\r
640 \r
641                                                         // Decrease the range content to exclude particial\r
642                                                         // selected node on the start which doesn't have\r
643                                                         // visual impact. ( #3231 )\r
644                                                         while ( true )\r
645                                                         {\r
646                                                                 var startContainer = range.startContainer,\r
647                                                                         startOffset = range.startOffset;\r
648                                                                 // Limit the fix only to non-block elements.(#3950)\r
649                                                                 if ( startOffset == ( startContainer.getChildCount ?\r
650                                                                          startContainer.getChildCount() : startContainer.getLength() )\r
651                                                                          && !startContainer.isBlockBoundary() )\r
652                                                                         range.setStartAfter( startContainer );\r
653                                                                 else break;\r
654                                                         }\r
655 \r
656                                                         node = range.startContainer;\r
657 \r
658                                                         if ( node.type != CKEDITOR.NODE_ELEMENT )\r
659                                                                 return node.getParent();\r
660 \r
661                                                         node = node.getChild( range.startOffset );\r
662 \r
663                                                         if ( !node || node.type != CKEDITOR.NODE_ELEMENT )\r
664                                                                 return range.startContainer;\r
665 \r
666                                                         var child = node.getFirst();\r
667                                                         while (  child && child.type == CKEDITOR.NODE_ELEMENT )\r
668                                                         {\r
669                                                                 node = child;\r
670                                                                 child = child.getFirst();\r
671                                                         }\r
672 \r
673                                                         return node;\r
674                                                 }\r
675                                         }\r
676 \r
677                                         if ( CKEDITOR.env.ie )\r
678                                         {\r
679                                                 range = sel.createRange();\r
680                                                 range.collapse( true );\r
681 \r
682                                                 node = range.parentElement();\r
683                                         }\r
684                                         else\r
685                                         {\r
686                                                 node = sel.anchorNode;\r
687 \r
688                                                 if ( node && node.nodeType != 1 )\r
689                                                         node = node.parentNode;\r
690                                         }\r
691                         }\r
692 \r
693                         return cache.startElement = ( node ? new CKEDITOR.dom.element( node ) : null );\r
694                 },\r
695 \r
696                 /**\r
697                  * Gets the current selected element.\r
698                  * @returns {CKEDITOR.dom.element} The selected element. Null if no\r
699                  *              selection is available or the selection type is not\r
700                  *              {@link CKEDITOR.SELECTION_ELEMENT}.\r
701                  * @example\r
702                  * var element = editor.getSelection().<b>getSelectedElement()</b>;\r
703                  * alert( element.getName() );\r
704                  */\r
705                 getSelectedElement : function()\r
706                 {\r
707                         var cache = this._.cache;\r
708                         if ( cache.selectedElement !== undefined )\r
709                                 return cache.selectedElement;\r
710 \r
711                         var node;\r
712 \r
713                         if ( this.getType() == CKEDITOR.SELECTION_ELEMENT )\r
714                         {\r
715                                 var sel = this.getNative();\r
716 \r
717                                 if ( CKEDITOR.env.ie )\r
718                                 {\r
719                                         try\r
720                                         {\r
721                                                 node = sel.createRange().item(0);\r
722                                         }\r
723                                         catch(e) {}\r
724                                 }\r
725                                 else\r
726                                 {\r
727                                         var range = sel.getRangeAt( 0 );\r
728                                         node = range.startContainer.childNodes[ range.startOffset ];\r
729                                 }\r
730                         }\r
731 \r
732                         return cache.selectedElement = ( node ? new CKEDITOR.dom.element( node ) : null );\r
733                 },\r
734 \r
735                 lock : function()\r
736                 {\r
737                         // Call all cacheable function.\r
738                         this.getRanges();\r
739                         this.getStartElement();\r
740                         this.getSelectedElement();\r
741 \r
742                         // The native selection is not available when locked.\r
743                         this._.cache.nativeSel = {};\r
744 \r
745                         this.isLocked = true;\r
746 \r
747                         // Save this selection inside the DOM document.\r
748                         this.document.setCustomData( 'cke_locked_selection', this );\r
749                 },\r
750 \r
751                 unlock : function( restore )\r
752                 {\r
753                         var doc = this.document,\r
754                                 lockedSelection = doc.getCustomData( 'cke_locked_selection' );\r
755 \r
756                         if ( lockedSelection )\r
757                         {\r
758                                 doc.setCustomData( 'cke_locked_selection', null );\r
759 \r
760                                 if ( restore )\r
761                                 {\r
762                                         var selectedElement = lockedSelection.getSelectedElement(),\r
763                                                 ranges = !selectedElement && lockedSelection.getRanges();\r
764 \r
765                                         this.isLocked = false;\r
766                                         this.reset();\r
767 \r
768                                         doc.getBody().focus();\r
769 \r
770                                         if ( selectedElement )\r
771                                                 this.selectElement( selectedElement );\r
772                                         else\r
773                                                 this.selectRanges( ranges );\r
774                                 }\r
775                         }\r
776 \r
777                         if  ( !lockedSelection || !restore )\r
778                         {\r
779                                 this.isLocked = false;\r
780                                 this.reset();\r
781                         }\r
782                 },\r
783 \r
784                 reset : function()\r
785                 {\r
786                         this._.cache = {};\r
787                 },\r
788 \r
789                 selectElement : function( element )\r
790                 {\r
791                         if ( this.isLocked )\r
792                         {\r
793                                 var range = new CKEDITOR.dom.range( this.document );\r
794                                 range.setStartBefore( element );\r
795                                 range.setEndAfter( element );\r
796 \r
797                                 this._.cache.selectedElement = element;\r
798                                 this._.cache.startElement = element;\r
799                                 this._.cache.ranges = [ range ];\r
800                                 this._.cache.type = CKEDITOR.SELECTION_ELEMENT;\r
801 \r
802                                 return;\r
803                         }\r
804 \r
805                         if ( CKEDITOR.env.ie )\r
806                         {\r
807                                 this.getNative().empty();\r
808 \r
809                                 try\r
810                                 {\r
811                                         // Try to select the node as a control.\r
812                                         range = this.document.$.body.createControlRange();\r
813                                         range.addElement( element.$ );\r
814                                         range.select();\r
815                                 }\r
816                                 catch(e)\r
817                                 {\r
818                                         // If failed, select it as a text range.\r
819                                         range = this.document.$.body.createTextRange();\r
820                                         range.moveToElementText( element.$ );\r
821                                         range.select();\r
822                                 }\r
823 \r
824                                 this.reset();\r
825                         }\r
826                         else\r
827                         {\r
828                                 // Create the range for the element.\r
829                                 range = this.document.$.createRange();\r
830                                 range.selectNode( element.$ );\r
831 \r
832                                 // Select the range.\r
833                                 var sel = this.getNative();\r
834                                 sel.removeAllRanges();\r
835                                 sel.addRange( range );\r
836 \r
837                                 this.reset();\r
838                         }\r
839                 },\r
840 \r
841                 selectRanges : function( ranges )\r
842                 {\r
843                         if ( this.isLocked )\r
844                         {\r
845                                 this._.cache.selectedElement = null;\r
846                                 this._.cache.startElement = ranges[ 0 ].getTouchedStartNode();\r
847                                 this._.cache.ranges = ranges;\r
848                                 this._.cache.type = CKEDITOR.SELECTION_TEXT;\r
849 \r
850                                 return;\r
851                         }\r
852 \r
853                         if ( CKEDITOR.env.ie )\r
854                         {\r
855                                 // IE doesn't accept multiple ranges selection, so we just\r
856                                 // select the first one.\r
857                                 if ( ranges[ 0 ] )\r
858                                         ranges[ 0 ].select();\r
859 \r
860                                 this.reset();\r
861                         }\r
862                         else\r
863                         {\r
864                                 var sel = this.getNative();\r
865                                 sel.removeAllRanges();\r
866 \r
867                                 for ( var i = 0 ; i < ranges.length ; i++ )\r
868                                 {\r
869                                         var range = ranges[ i ];\r
870                                         var nativeRange = this.document.$.createRange();\r
871                                         var startContainer = range.startContainer;\r
872 \r
873                                         // In FF2, if we have a collapsed range, inside an empty\r
874                                         // element, we must add something to it otherwise the caret\r
875                                         // will not be visible.\r
876                                         if ( range.collapsed &&\r
877                                                 ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) &&\r
878                                                 startContainer.type == CKEDITOR.NODE_ELEMENT &&\r
879                                                 !startContainer.getChildCount() )\r
880                                         {\r
881                                                 startContainer.appendText( '' );\r
882                                         }\r
883 \r
884                                         nativeRange.setStart( startContainer.$, range.startOffset );\r
885                                         nativeRange.setEnd( range.endContainer.$, range.endOffset );\r
886 \r
887                                         // Select the range.\r
888                                         sel.addRange( nativeRange );\r
889                                 }\r
890 \r
891                                 this.reset();\r
892                         }\r
893                 },\r
894 \r
895                 createBookmarks : function( serializable )\r
896                 {\r
897                         var retval = [],\r
898                                 ranges = this.getRanges(),\r
899                                 length = ranges.length,\r
900                                 bookmark;\r
901                         for ( var i = 0; i < length ; i++ )\r
902                         {\r
903                             retval.push( bookmark = ranges[ i ].createBookmark( serializable, true ) );\r
904 \r
905                                 serializable = bookmark.serializable;\r
906 \r
907                                 var bookmarkStart = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode,\r
908                                         bookmarkEnd = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode;\r
909 \r
910                             // Updating the offset values for rest of ranges which have been mangled(#3256).\r
911                             for ( var j = i + 1 ; j < length ; j++ )\r
912                             {\r
913                                 var dirtyRange = ranges[ j ],\r
914                                        rangeStart = dirtyRange.startContainer,\r
915                                        rangeEnd = dirtyRange.endContainer;\r
916 \r
917                                rangeStart.equals( bookmarkStart.getParent() ) && dirtyRange.startOffset++;\r
918                                rangeStart.equals( bookmarkEnd.getParent() ) && dirtyRange.startOffset++;\r
919                                rangeEnd.equals( bookmarkStart.getParent() ) && dirtyRange.endOffset++;\r
920                                rangeEnd.equals( bookmarkEnd.getParent() ) && dirtyRange.endOffset++;\r
921                             }\r
922                         }\r
923 \r
924                         return retval;\r
925                 },\r
926 \r
927                 createBookmarks2 : function( normalized )\r
928                 {\r
929                         var bookmarks = [],\r
930                                 ranges = this.getRanges();\r
931 \r
932                         for ( var i = 0 ; i < ranges.length ; i++ )\r
933                                 bookmarks.push( ranges[i].createBookmark2( normalized ) );\r
934 \r
935                         return bookmarks;\r
936                 },\r
937 \r
938                 selectBookmarks : function( bookmarks )\r
939                 {\r
940                         var ranges = [];\r
941                         for ( var i = 0 ; i < bookmarks.length ; i++ )\r
942                         {\r
943                                 var range = new CKEDITOR.dom.range( this.document );\r
944                                 range.moveToBookmark( bookmarks[i] );\r
945                                 ranges.push( range );\r
946                         }\r
947                         this.selectRanges( ranges );\r
948                         return this;\r
949                 },\r
950 \r
951                 getCommonAncestor : function()\r
952                 {\r
953                         var ranges = this.getRanges(),\r
954                                 startNode = ranges[ 0 ].startContainer,\r
955                                 endNode = ranges[ ranges.length - 1 ].endContainer;\r
956                         return startNode.getCommonAncestor( endNode );\r
957                 },\r
958 \r
959                 // Moving scroll bar to the current selection's start position.\r
960                 scrollIntoView : function()\r
961                 {\r
962                         // If we have split the block, adds a temporary span at the\r
963                         // range position and scroll relatively to it.\r
964                         var start = this.getStartElement();\r
965                         start.scrollIntoView();\r
966                 }\r
967         };\r
968 })();\r
969 ( function()\r
970 {\r
971 var notWhitespaces = CKEDITOR.dom.walker.whitespaces( true );\r
972 var fillerTextRegex = /\ufeff|\u00a0/;\r
973 \r
974 CKEDITOR.dom.range.prototype.select =\r
975         CKEDITOR.env.ie ?\r
976                 // V2\r
977                 function( forceExpand )\r
978                 {\r
979                         var collapsed = this.collapsed;\r
980                         var isStartMarkerAlone;\r
981                         var dummySpan;\r
982 \r
983                         var bookmark = this.createBookmark();\r
984 \r
985                         // Create marker tags for the start and end boundaries.\r
986                         var startNode = bookmark.startNode;\r
987 \r
988                         var endNode;\r
989                         if ( !collapsed )\r
990                                 endNode = bookmark.endNode;\r
991 \r
992                         // Create the main range which will be used for the selection.\r
993                         var ieRange = this.document.$.body.createTextRange();\r
994 \r
995                         // Position the range at the start boundary.\r
996                         ieRange.moveToElementText( startNode.$ );\r
997                         ieRange.moveStart( 'character', 1 );\r
998 \r
999                         if ( endNode )\r
1000                         {\r
1001                                 // Create a tool range for the end.\r
1002                                 var ieRangeEnd = this.document.$.body.createTextRange();\r
1003 \r
1004                                 // Position the tool range at the end.\r
1005                                 ieRangeEnd.moveToElementText( endNode.$ );\r
1006 \r
1007                                 // Move the end boundary of the main range to match the tool range.\r
1008                                 ieRange.setEndPoint( 'EndToEnd', ieRangeEnd );\r
1009                                 ieRange.moveEnd( 'character', -1 );\r
1010                         }\r
1011                         else\r
1012                         {\r
1013                                 // The isStartMarkerAlone logic comes from V2. It guarantees that the lines\r
1014                                 // will expand and that the cursor will be blinking on the right place.\r
1015                                 // Actually, we are using this flag just to avoid using this hack in all\r
1016                                 // situations, but just on those needed.\r
1017                                 var next = startNode.getNext( notWhitespaces );\r
1018                                 isStartMarkerAlone = ( !( next && next.getText && next.getText().match( fillerTextRegex ) )     // already a filler there?\r
1019                                                                           && ( forceExpand || !startNode.hasPrevious() || ( startNode.getPrevious().is && startNode.getPrevious().is( 'br' ) ) ) );\r
1020 \r
1021                                 // Append a temporary <span>&#65279;</span> before the selection.\r
1022                                 // This is needed to avoid IE destroying selections inside empty\r
1023                                 // inline elements, like <b></b> (#253).\r
1024                                 // It is also needed when placing the selection right after an inline\r
1025                                 // element to avoid the selection moving inside of it.\r
1026                                 dummySpan = this.document.createElement( 'span' );\r
1027                                 dummySpan.setHtml( '&#65279;' );        // Zero Width No-Break Space (U+FEFF). See #1359.\r
1028                                 dummySpan.insertBefore( startNode );\r
1029 \r
1030                                 if ( isStartMarkerAlone )\r
1031                                 {\r
1032                                         // To expand empty blocks or line spaces after <br>, we need\r
1033                                         // instead to have any char, which will be later deleted using the\r
1034                                         // selection.\r
1035                                         // \ufeff = Zero Width No-Break Space (U+FEFF). (#1359)\r
1036                                         this.document.createText( '\ufeff' ).insertBefore( startNode );\r
1037                                 }\r
1038                         }\r
1039 \r
1040                         // Remove the markers (reset the position, because of the changes in the DOM tree).\r
1041                         this.setStartBefore( startNode );\r
1042                         startNode.remove();\r
1043 \r
1044                         if ( collapsed )\r
1045                         {\r
1046                                 if ( isStartMarkerAlone )\r
1047                                 {\r
1048                                         // Move the selection start to include the temporary \ufeff.\r
1049                                         ieRange.moveStart( 'character', -1 );\r
1050 \r
1051                                         ieRange.select();\r
1052 \r
1053                                         // Remove our temporary stuff.\r
1054                                         this.document.$.selection.clear();\r
1055                                 }\r
1056                                 else\r
1057                                         ieRange.select();\r
1058 \r
1059                                 dummySpan.remove();\r
1060                         }\r
1061                         else\r
1062                         {\r
1063                                 this.setEndBefore( endNode );\r
1064                                 endNode.remove();\r
1065                                 ieRange.select();\r
1066                         }\r
1067                 }\r
1068         :\r
1069                 function()\r
1070                 {\r
1071                         var startContainer = this.startContainer;\r
1072 \r
1073                         // If we have a collapsed range, inside an empty element, we must add\r
1074                         // something to it, otherwise the caret will not be visible.\r
1075                         if ( this.collapsed && startContainer.type == CKEDITOR.NODE_ELEMENT && !startContainer.getChildCount() )\r
1076                                 startContainer.append( new CKEDITOR.dom.text( '' ) );\r
1077 \r
1078                         var nativeRange = this.document.$.createRange();\r
1079                         nativeRange.setStart( startContainer.$, this.startOffset );\r
1080 \r
1081                         try\r
1082                         {\r
1083                                 nativeRange.setEnd( this.endContainer.$, this.endOffset );\r
1084                         }\r
1085                         catch ( e )\r
1086                         {\r
1087                                 // There is a bug in Firefox implementation (it would be too easy\r
1088                                 // otherwise). The new start can't be after the end (W3C says it can).\r
1089                                 // So, let's create a new range and collapse it to the desired point.\r
1090                                 if ( e.toString().indexOf( 'NS_ERROR_ILLEGAL_VALUE' ) >= 0 )\r
1091                                 {\r
1092                                         this.collapse( true );\r
1093                                         nativeRange.setEnd( this.endContainer.$, this.endOffset );\r
1094                                 }\r
1095                                 else\r
1096                                         throw( e );\r
1097                         }\r
1098 \r
1099                         var selection = this.document.getSelection().getNative();\r
1100                         selection.removeAllRanges();\r
1101                         selection.addRange( nativeRange );\r
1102                 };\r
1103 } )();\r