Nation Notes module contributed by Z&H Healthcare.
[openemr.git] / library / custom_template / ckeditor / _source / core / dom / range.js
blob974999ed3fed805020bb271e9efff682e274ac77
1 /*
2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
3 For licensing, see LICENSE.html or http://ckeditor.com/license
4 */
6 /**
7  * @class
8  */
9 CKEDITOR.dom.range = function( document )
11         this.startContainer     = null;
12         this.startOffset        = null;
13         this.endContainer       = null;
14         this.endOffset          = null;
15         this.collapsed          = true;
17         this.document = document;
20 (function()
22         // Updates the "collapsed" property for the given range object.
23         var updateCollapsed = function( range )
24         {
25                 range.collapsed = (
26                         range.startContainer &&
27                         range.endContainer &&
28                         range.startContainer.equals( range.endContainer ) &&
29                         range.startOffset == range.endOffset );
30         };
32         // This is a shared function used to delete, extract and clone the range
33         // contents.
34         // V2
35         var execContentsAction = function( range, action, docFrag, mergeThen )
36         {
37                 range.optimizeBookmark();
39                 var startNode   = range.startContainer;
40                 var endNode             = range.endContainer;
42                 var startOffset = range.startOffset;
43                 var endOffset   = range.endOffset;
45                 var removeStartNode;
46                 var removeEndNode;
48                 // For text containers, we must simply split the node and point to the
49                 // second part. The removal will be handled by the rest of the code .
50                 if ( endNode.type == CKEDITOR.NODE_TEXT )
51                         endNode = endNode.split( endOffset );
52                 else
53                 {
54                         // If the end container has children and the offset is pointing
55                         // to a child, then we should start from it.
56                         if ( endNode.getChildCount() > 0 )
57                         {
58                                 // If the offset points after the last node.
59                                 if ( endOffset >= endNode.getChildCount() )
60                                 {
61                                         // Let's create a temporary node and mark it for removal.
62                                         endNode = endNode.append( range.document.createText( '' ) );
63                                         removeEndNode = true;
64                                 }
65                                 else
66                                         endNode = endNode.getChild( endOffset );
67                         }
68                 }
70                 // For text containers, we must simply split the node. The removal will
71                 // be handled by the rest of the code .
72                 if ( startNode.type == CKEDITOR.NODE_TEXT )
73                 {
74                         startNode.split( startOffset );
76                         // In cases the end node is the same as the start node, the above
77                         // splitting will also split the end, so me must move the end to
78                         // the second part of the split.
79                         if ( startNode.equals( endNode ) )
80                                 endNode = startNode.getNext();
81                 }
82                 else
83                 {
84                         // If the start container has children and the offset is pointing
85                         // to a child, then we should start from its previous sibling.
87                         // If the offset points to the first node, we don't have a
88                         // sibling, so let's use the first one, but mark it for removal.
89                         if ( !startOffset )
90                         {
91                                 // Let's create a temporary node and mark it for removal.
92                                 startNode = startNode.getFirst().insertBeforeMe( range.document.createText( '' ) );
93                                 removeStartNode = true;
94                         }
95                         else if ( startOffset >= startNode.getChildCount() )
96                         {
97                                 // Let's create a temporary node and mark it for removal.
98                                 startNode = startNode.append( range.document.createText( '' ) );
99                                 removeStartNode = true;
100                         }
101                         else
102                                 startNode = startNode.getChild( startOffset ).getPrevious();
103                 }
105                 // Get the parent nodes tree for the start and end boundaries.
106                 var startParents        = startNode.getParents();
107                 var endParents          = endNode.getParents();
109                 // Compare them, to find the top most siblings.
110                 var i, topStart, topEnd;
112                 for ( i = 0 ; i < startParents.length ; i++ )
113                 {
114                         topStart = startParents[ i ];
115                         topEnd = endParents[ i ];
117                         // The compared nodes will match until we find the top most
118                         // siblings (different nodes that have the same parent).
119                         // "i" will hold the index in the parents array for the top
120                         // most element.
121                         if ( !topStart.equals( topEnd ) )
122                                 break;
123                 }
125                 var clone = docFrag, levelStartNode, levelClone, currentNode, currentSibling;
127                 // Remove all successive sibling nodes for every node in the
128                 // startParents tree.
129                 for ( var j = i ; j < startParents.length ; j++ )
130                 {
131                         levelStartNode = startParents[j];
133                         // For Extract and Clone, we must clone this level.
134                         if ( clone && !levelStartNode.equals( startNode ) )             // action = 0 = Delete
135                                 levelClone = clone.append( levelStartNode.clone() );
137                         currentNode = levelStartNode.getNext();
139                         while ( currentNode )
140                         {
141                                 // Stop processing when the current node matches a node in the
142                                 // endParents tree or if it is the endNode.
143                                 if ( currentNode.equals( endParents[ j ] ) || currentNode.equals( endNode ) )
144                                         break;
146                                 // Cache the next sibling.
147                                 currentSibling = currentNode.getNext();
149                                 // If cloning, just clone it.
150                                 if ( action == 2 )      // 2 = Clone
151                                         clone.append( currentNode.clone( true ) );
152                                 else
153                                 {
154                                         // Both Delete and Extract will remove the node.
155                                         currentNode.remove();
157                                         // When Extracting, move the removed node to the docFrag.
158                                         if ( action == 1 )      // 1 = Extract
159                                                 clone.append( currentNode );
160                                 }
162                                 currentNode = currentSibling;
163                         }
165                         if ( clone )
166                                 clone = levelClone;
167                 }
169                 clone = docFrag;
171                 // Remove all previous sibling nodes for every node in the
172                 // endParents tree.
173                 for ( var k = i ; k < endParents.length ; k++ )
174                 {
175                         levelStartNode = endParents[ k ];
177                         // For Extract and Clone, we must clone this level.
178                         if ( action > 0 && !levelStartNode.equals( endNode ) )          // action = 0 = Delete
179                                 levelClone = clone.append( levelStartNode.clone() );
181                         // The processing of siblings may have already been done by the parent.
182                         if ( !startParents[ k ] || levelStartNode.$.parentNode != startParents[ k ].$.parentNode )
183                         {
184                                 currentNode = levelStartNode.getPrevious();
186                                 while ( currentNode )
187                                 {
188                                         // Stop processing when the current node matches a node in the
189                                         // startParents tree or if it is the startNode.
190                                         if ( currentNode.equals( startParents[ k ] ) || currentNode.equals( startNode ) )
191                                                 break;
193                                         // Cache the next sibling.
194                                         currentSibling = currentNode.getPrevious();
196                                         // If cloning, just clone it.
197                                         if ( action == 2 )      // 2 = Clone
198                                                 clone.$.insertBefore( currentNode.$.cloneNode( true ), clone.$.firstChild ) ;
199                                         else
200                                         {
201                                                 // Both Delete and Extract will remove the node.
202                                                 currentNode.remove();
204                                                 // When Extracting, mode the removed node to the docFrag.
205                                                 if ( action == 1 )      // 1 = Extract
206                                                         clone.$.insertBefore( currentNode.$, clone.$.firstChild );
207                                         }
209                                         currentNode = currentSibling;
210                                 }
211                         }
213                         if ( clone )
214                                 clone = levelClone;
215                 }
217                 if ( action == 2 )              // 2 = Clone.
218                 {
219                         // No changes in the DOM should be done, so fix the split text (if any).
221                         var startTextNode = range.startContainer;
222                         if ( startTextNode.type == CKEDITOR.NODE_TEXT )
223                         {
224                                 startTextNode.$.data += startTextNode.$.nextSibling.data;
225                                 startTextNode.$.parentNode.removeChild( startTextNode.$.nextSibling );
226                         }
228                         var endTextNode = range.endContainer;
229                         if ( endTextNode.type == CKEDITOR.NODE_TEXT && endTextNode.$.nextSibling )
230                         {
231                                 endTextNode.$.data += endTextNode.$.nextSibling.data;
232                                 endTextNode.$.parentNode.removeChild( endTextNode.$.nextSibling );
233                         }
234                 }
235                 else
236                 {
237                         // Collapse the range.
239                         // If a node has been partially selected, collapse the range between
240                         // topStart and topEnd. Otherwise, simply collapse it to the start. (W3C specs).
241                         if ( topStart && topEnd && ( startNode.$.parentNode != topStart.$.parentNode || endNode.$.parentNode != topEnd.$.parentNode ) )
242                         {
243                                 var endIndex = topEnd.getIndex();
245                                 // If the start node is to be removed, we must correct the
246                                 // index to reflect the removal.
247                                 if ( removeStartNode && topEnd.$.parentNode == startNode.$.parentNode )
248                                         endIndex--;
250                                 // Merge splitted parents.
251                                 if ( mergeThen && topStart.type == CKEDITOR.NODE_ELEMENT )
252                                 {
253                                         var span = CKEDITOR.dom.element.createFromHtml( '<span ' +
254                                                 'data-cke-bookmark="1" style="display:none">&nbsp;</span>', range.document );
255                                         span.insertAfter( topStart );
256                                         topStart.mergeSiblings( false );
257                                         range.moveToBookmark( { startNode : span } );
258                                 }
259                                 else
260                                         range.setStart( topEnd.getParent(), endIndex );
261                         }
263                         // Collapse it to the start.
264                         range.collapse( true );
265                 }
267                 // Cleanup any marked node.
268                 if ( removeStartNode )
269                         startNode.remove();
271                 if ( removeEndNode && endNode.$.parentNode )
272                         endNode.remove();
273         };
275         var inlineChildReqElements = { abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 };
277         // Creates the appropriate node evaluator for the dom walker used inside
278         // check(Start|End)OfBlock.
279         function getCheckStartEndBlockEvalFunction( isStart )
280         {
281                 var hadBr = false, bookmarkEvaluator = CKEDITOR.dom.walker.bookmark( true );
282                 return function( node )
283                 {
284                         // First ignore bookmark nodes.
285                         if ( bookmarkEvaluator( node ) )
286                                 return true;
288                         if ( node.type == CKEDITOR.NODE_TEXT )
289                         {
290                                 // If there's any visible text, then we're not at the start.
291                                 if ( CKEDITOR.tools.trim( node.getText() ).length )
292                                         return false;
293                         }
294                         else if ( node.type == CKEDITOR.NODE_ELEMENT )
295                         {
296                                 // If there are non-empty inline elements (e.g. <img />), then we're not
297                                 // at the start.
298                                 if ( !inlineChildReqElements[ node.getName() ] )
299                                 {
300                                         // If we're working at the end-of-block, forgive the first <br /> in non-IE
301                                         // browsers.
302                                         if ( !isStart && !CKEDITOR.env.ie && node.getName() == 'br' && !hadBr )
303                                                 hadBr = true;
304                                         else
305                                                 return false;
306                                 }
307                         }
308                         return true;
309                 };
310         }
312         // Evaluator for CKEDITOR.dom.element::checkBoundaryOfElement, reject any
313         // text node and non-empty elements unless it's being bookmark text.
314         function elementBoundaryEval( node )
315         {
316                 // Reject any text node unless it's being bookmark
317                 // OR it's spaces. (#3883)
318                 return node.type != CKEDITOR.NODE_TEXT
319                             && node.getName() in CKEDITOR.dtd.$removeEmpty
320                             || !CKEDITOR.tools.trim( node.getText() )
321                             || !!node.getParent().data( 'cke-bookmark' );
322         }
324         var whitespaceEval = new CKEDITOR.dom.walker.whitespaces(),
325                 bookmarkEval = new CKEDITOR.dom.walker.bookmark();
327         function nonWhitespaceOrBookmarkEval( node )
328         {
329                 // Whitespaces and bookmark nodes are to be ignored.
330                 return !whitespaceEval( node ) && !bookmarkEval( node );
331         }
333         CKEDITOR.dom.range.prototype =
334         {
335                 clone : function()
336                 {
337                         var clone = new CKEDITOR.dom.range( this.document );
339                         clone.startContainer = this.startContainer;
340                         clone.startOffset = this.startOffset;
341                         clone.endContainer = this.endContainer;
342                         clone.endOffset = this.endOffset;
343                         clone.collapsed = this.collapsed;
345                         return clone;
346                 },
348                 collapse : function( toStart )
349                 {
350                         if ( toStart )
351                         {
352                                 this.endContainer       = this.startContainer;
353                                 this.endOffset          = this.startOffset;
354                         }
355                         else
356                         {
357                                 this.startContainer     = this.endContainer;
358                                 this.startOffset        = this.endOffset;
359                         }
361                         this.collapsed = true;
362                 },
364                 /**
365                  *  The content nodes of the range are cloned and added to a document fragment, which is returned.
366                  *  <strong> Note: </strong> Text selection may lost after invoking this method. (caused by text node splitting).
367                  */
368                 cloneContents : function()
369                 {
370                         var docFrag = new CKEDITOR.dom.documentFragment( this.document );
372                         if ( !this.collapsed )
373                                 execContentsAction( this, 2, docFrag );
375                         return docFrag;
376                 },
378                 /**
379                  * Deletes the content nodes of the range permanently from the DOM tree.
380                  * @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
381                  */
382                 deleteContents : function( mergeThen )
383                 {
384                         if ( this.collapsed )
385                                 return;
387                         execContentsAction( this, 0, null, mergeThen );
388                 },
390                 /**
391                  *  The content nodes of the range are cloned and added to a document fragment,
392                  * meanwhile they're removed permanently from the DOM tree.
393                  * @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
394                  */
395                 extractContents : function( mergeThen )
396                 {
397                         var docFrag = new CKEDITOR.dom.documentFragment( this.document );
399                         if ( !this.collapsed )
400                                 execContentsAction( this, 1, docFrag, mergeThen );
402                         return docFrag;
403                 },
405                 /**
406                  * Creates a bookmark object, which can be later used to restore the
407                  * range by using the moveToBookmark function.
408                  * This is an "intrusive" way to create a bookmark. It includes <span> tags
409                  * in the range boundaries. The advantage of it is that it is possible to
410                  * handle DOM mutations when moving back to the bookmark.
411                  * Attention: the inclusion of nodes in the DOM is a design choice and
412                  * should not be changed as there are other points in the code that may be
413                  * using those nodes to perform operations. See GetBookmarkNode.
414                  * @param {Boolean} [serializable] Indicates that the bookmark nodes
415                  *              must contain ids, which can be used to restore the range even
416                  *              when these nodes suffer mutations (like a clonation or innerHTML
417                  *              change).
418                  * @returns {Object} And object representing a bookmark.
419                  */
420                 createBookmark : function( serializable )
421                 {
422                         var startNode, endNode;
423                         var baseId;
424                         var clone;
425                         var collapsed = this.collapsed;
427                         startNode = this.document.createElement( 'span' );
428                         startNode.data( 'cke-bookmark', 1 );
429                         startNode.setStyle( 'display', 'none' );
431                         // For IE, it must have something inside, otherwise it may be
432                         // removed during DOM operations.
433                         startNode.setHtml( '&nbsp;' );
435                         if ( serializable )
436                         {
437                                 baseId = 'cke_bm_' + CKEDITOR.tools.getNextNumber();
438                                 startNode.setAttribute( 'id', baseId + 'S' );
439                         }
441                         // If collapsed, the endNode will not be created.
442                         if ( !collapsed )
443                         {
444                                 endNode = startNode.clone();
445                                 endNode.setHtml( '&nbsp;' );
447                                 if ( serializable )
448                                         endNode.setAttribute( 'id', baseId + 'E' );
450                                 clone = this.clone();
451                                 clone.collapse();
452                                 clone.insertNode( endNode );
453                         }
455                         clone = this.clone();
456                         clone.collapse( true );
457                         clone.insertNode( startNode );
459                         // Update the range position.
460                         if ( endNode )
461                         {
462                                 this.setStartAfter( startNode );
463                                 this.setEndBefore( endNode );
464                         }
465                         else
466                                 this.moveToPosition( startNode, CKEDITOR.POSITION_AFTER_END );
468                         return {
469                                 startNode : serializable ? baseId + 'S' : startNode,
470                                 endNode : serializable ? baseId + 'E' : endNode,
471                                 serializable : serializable,
472                                 collapsed : collapsed
473                         };
474                 },
476                 /**
477                  * Creates a "non intrusive" and "mutation sensible" bookmark. This
478                  * kind of bookmark should be used only when the DOM is supposed to
479                  * remain stable after its creation.
480                  * @param {Boolean} [normalized] Indicates that the bookmark must
481                  *              normalized. When normalized, the successive text nodes are
482                  *              considered a single node. To sucessful load a normalized
483                  *              bookmark, the DOM tree must be also normalized before calling
484                  *              moveToBookmark.
485                  * @returns {Object} An object representing the bookmark.
486                  */
487                 createBookmark2 : function( normalized )
488                 {
489                         var startContainer      = this.startContainer,
490                                 endContainer    = this.endContainer;
492                         var startOffset = this.startOffset,
493                                 endOffset       = this.endOffset;
495                         var collapsed = this.collapsed;
497                         var child, previous;
499                         // If there is no range then get out of here.
500                         // It happens on initial load in Safari #962 and if the editor it's
501                         // hidden also in Firefox
502                         if ( !startContainer || !endContainer )
503                                 return { start : 0, end : 0 };
505                         if ( normalized )
506                         {
507                                 // Find out if the start is pointing to a text node that will
508                                 // be normalized.
509                                 if ( startContainer.type == CKEDITOR.NODE_ELEMENT )
510                                 {
511                                         child = startContainer.getChild( startOffset );
513                                         // In this case, move the start information to that text
514                                         // node.
515                                         if ( child && child.type == CKEDITOR.NODE_TEXT
516                                                         && startOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
517                                         {
518                                                 startContainer = child;
519                                                 startOffset = 0;
520                                         }
521                                 }
523                                 // Normalize the start.
524                                 while ( startContainer.type == CKEDITOR.NODE_TEXT
525                                                 && ( previous = startContainer.getPrevious() )
526                                                 && previous.type == CKEDITOR.NODE_TEXT )
527                                 {
528                                         startContainer = previous;
529                                         startOffset += previous.getLength();
530                                 }
532                                 // Process the end only if not normalized.
533                                 if ( !collapsed )
534                                 {
535                                         // Find out if the start is pointing to a text node that
536                                         // will be normalized.
537                                         if ( endContainer.type == CKEDITOR.NODE_ELEMENT )
538                                         {
539                                                 child = endContainer.getChild( endOffset );
541                                                 // In this case, move the start information to that
542                                                 // text node.
543                                                 if ( child && child.type == CKEDITOR.NODE_TEXT
544                                                                 && endOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
545                                                 {
546                                                         endContainer = child;
547                                                         endOffset = 0;
548                                                 }
549                                         }
551                                         // Normalize the end.
552                                         while ( endContainer.type == CKEDITOR.NODE_TEXT
553                                                         && ( previous = endContainer.getPrevious() )
554                                                         && previous.type == CKEDITOR.NODE_TEXT )
555                                         {
556                                                 endContainer = previous;
557                                                 endOffset += previous.getLength();
558                                         }
559                                 }
560                         }
562                         return {
563                                 start           : startContainer.getAddress( normalized ),
564                                 end                     : collapsed ? null : endContainer.getAddress( normalized ),
565                                 startOffset     : startOffset,
566                                 endOffset       : endOffset,
567                                 normalized      : normalized,
568                                 collapsed       : collapsed,
569                                 is2                     : true          // It's a createBookmark2 bookmark.
570                         };
571                 },
573                 moveToBookmark : function( bookmark )
574                 {
575                         if ( bookmark.is2 )             // Created with createBookmark2().
576                         {
577                                 // Get the start information.
578                                 var startContainer      = this.document.getByAddress( bookmark.start, bookmark.normalized ),
579                                         startOffset     = bookmark.startOffset;
581                                 // Get the end information.
582                                 var endContainer        = bookmark.end && this.document.getByAddress( bookmark.end, bookmark.normalized ),
583                                         endOffset       = bookmark.endOffset;
585                                 // Set the start boundary.
586                                 this.setStart( startContainer, startOffset );
588                                 // Set the end boundary. If not available, collapse it.
589                                 if ( endContainer )
590                                         this.setEnd( endContainer, endOffset );
591                                 else
592                                         this.collapse( true );
593                         }
594                         else                                    // Created with createBookmark().
595                         {
596                                 var serializable = bookmark.serializable,
597                                         startNode       = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode,
598                                         endNode         = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode;
600                                 // Set the range start at the bookmark start node position.
601                                 this.setStartBefore( startNode );
603                                 // Remove it, because it may interfere in the setEndBefore call.
604                                 startNode.remove();
606                                 // Set the range end at the bookmark end node position, or simply
607                                 // collapse it if it is not available.
608                                 if ( endNode )
609                                 {
610                                         this.setEndBefore( endNode );
611                                         endNode.remove();
612                                 }
613                                 else
614                                         this.collapse( true );
615                         }
616                 },
618                 getBoundaryNodes : function()
619                 {
620                         var startNode = this.startContainer,
621                                 endNode = this.endContainer,
622                                 startOffset = this.startOffset,
623                                 endOffset = this.endOffset,
624                                 childCount;
626                         if ( startNode.type == CKEDITOR.NODE_ELEMENT )
627                         {
628                                 childCount = startNode.getChildCount();
629                                 if ( childCount > startOffset )
630                                         startNode = startNode.getChild( startOffset );
631                                 else if ( childCount < 1 )
632                                         startNode = startNode.getPreviousSourceNode();
633                                 else            // startOffset > childCount but childCount is not 0
634                                 {
635                                         // Try to take the node just after the current position.
636                                         startNode = startNode.$;
637                                         while ( startNode.lastChild )
638                                                 startNode = startNode.lastChild;
639                                         startNode = new CKEDITOR.dom.node( startNode );
641                                         // Normally we should take the next node in DFS order. But it
642                                         // is also possible that we've already reached the end of
643                                         // document.
644                                         startNode = startNode.getNextSourceNode() || startNode;
645                                 }
646                         }
647                         if ( endNode.type == CKEDITOR.NODE_ELEMENT )
648                         {
649                                 childCount = endNode.getChildCount();
650                                 if ( childCount > endOffset )
651                                         endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true );
652                                 else if ( childCount < 1 )
653                                         endNode = endNode.getPreviousSourceNode();
654                                 else            // endOffset > childCount but childCount is not 0
655                                 {
656                                         // Try to take the node just before the current position.
657                                         endNode = endNode.$;
658                                         while ( endNode.lastChild )
659                                                 endNode = endNode.lastChild;
660                                         endNode = new CKEDITOR.dom.node( endNode );
661                                 }
662                         }
664                         // Sometimes the endNode will come right before startNode for collapsed
665                         // ranges. Fix it. (#3780)
666                         if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING )
667                                 startNode = endNode;
669                         return { startNode : startNode, endNode : endNode };
670                 },
672                 /**
673                  * Find the node which fully contains the range.
674                  * @param includeSelf
675                  * @param {Boolean} ignoreTextNode Whether ignore CKEDITOR.NODE_TEXT type.
676                  */
677                 getCommonAncestor : function( includeSelf , ignoreTextNode )
678                 {
679                         var start = this.startContainer,
680                                 end = this.endContainer,
681                                 ancestor;
683                         if ( start.equals( end ) )
684                         {
685                                 if ( includeSelf
686                                                 && start.type == CKEDITOR.NODE_ELEMENT
687                                                 && this.startOffset == this.endOffset - 1 )
688                                         ancestor = start.getChild( this.startOffset );
689                                 else
690                                         ancestor = start;
691                         }
692                         else
693                                 ancestor = start.getCommonAncestor( end );
695                         return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor;
696                 },
698                 /**
699                  * Transforms the startContainer and endContainer properties from text
700                  * nodes to element nodes, whenever possible. This is actually possible
701                  * if either of the boundary containers point to a text node, and its
702                  * offset is set to zero, or after the last char in the node.
703                  */
704                 optimize : function()
705                 {
706                         var container = this.startContainer;
707                         var offset = this.startOffset;
709                         if ( container.type != CKEDITOR.NODE_ELEMENT )
710                         {
711                                 if ( !offset )
712                                         this.setStartBefore( container );
713                                 else if ( offset >= container.getLength() )
714                                         this.setStartAfter( container );
715                         }
717                         container = this.endContainer;
718                         offset = this.endOffset;
720                         if ( container.type != CKEDITOR.NODE_ELEMENT )
721                         {
722                                 if ( !offset )
723                                         this.setEndBefore( container );
724                                 else if ( offset >= container.getLength() )
725                                         this.setEndAfter( container );
726                         }
727                 },
729                 /**
730                  * Move the range out of bookmark nodes if they'd been the container.
731                  */
732                 optimizeBookmark: function()
733                 {
734                         var startNode = this.startContainer,
735                                 endNode = this.endContainer;
737                         if ( startNode.is && startNode.is( 'span' )
738                                 && startNode.data( 'cke-bookmark' ) )
739                                 this.setStartAt( startNode, CKEDITOR.POSITION_BEFORE_START );
740                         if ( endNode && endNode.is && endNode.is( 'span' )
741                                 && endNode.data( 'cke-bookmark' ) )
742                                 this.setEndAt( endNode,  CKEDITOR.POSITION_AFTER_END );
743                 },
745                 trim : function( ignoreStart, ignoreEnd )
746                 {
747                         var startContainer = this.startContainer,
748                                 startOffset = this.startOffset,
749                                 collapsed = this.collapsed;
750                         if ( ( !ignoreStart || collapsed )
751                                  && startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
752                         {
753                                 // If the offset is zero, we just insert the new node before
754                                 // the start.
755                                 if ( !startOffset )
756                                 {
757                                         startOffset = startContainer.getIndex();
758                                         startContainer = startContainer.getParent();
759                                 }
760                                 // If the offset is at the end, we'll insert it after the text
761                                 // node.
762                                 else if ( startOffset >= startContainer.getLength() )
763                                 {
764                                         startOffset = startContainer.getIndex() + 1;
765                                         startContainer = startContainer.getParent();
766                                 }
767                                 // In other case, we split the text node and insert the new
768                                 // node at the split point.
769                                 else
770                                 {
771                                         var nextText = startContainer.split( startOffset );
773                                         startOffset = startContainer.getIndex() + 1;
774                                         startContainer = startContainer.getParent();
776                                         // Check all necessity of updating the end boundary.
777                                         if ( this.startContainer.equals( this.endContainer ) )
778                                                 this.setEnd( nextText, this.endOffset - this.startOffset );
779                                         else if ( startContainer.equals( this.endContainer ) )
780                                                 this.endOffset += 1;
781                                 }
783                                 this.setStart( startContainer, startOffset );
785                                 if ( collapsed )
786                                 {
787                                         this.collapse( true );
788                                         return;
789                                 }
790                         }
792                         var endContainer = this.endContainer;
793                         var endOffset = this.endOffset;
795                         if ( !( ignoreEnd || collapsed )
796                                  && endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
797                         {
798                                 // If the offset is zero, we just insert the new node before
799                                 // the start.
800                                 if ( !endOffset )
801                                 {
802                                         endOffset = endContainer.getIndex();
803                                         endContainer = endContainer.getParent();
804                                 }
805                                 // If the offset is at the end, we'll insert it after the text
806                                 // node.
807                                 else if ( endOffset >= endContainer.getLength() )
808                                 {
809                                         endOffset = endContainer.getIndex() + 1;
810                                         endContainer = endContainer.getParent();
811                                 }
812                                 // In other case, we split the text node and insert the new
813                                 // node at the split point.
814                                 else
815                                 {
816                                         endContainer.split( endOffset );
818                                         endOffset = endContainer.getIndex() + 1;
819                                         endContainer = endContainer.getParent();
820                                 }
822                                 this.setEnd( endContainer, endOffset );
823                         }
824                 },
826                 /**
827                  * Expands the range so that partial units are completely contained.
828                  * @param unit {Number} The unit type to expand with.
829                  * @param {Boolean} [excludeBrs=false] Whether include line-breaks when expanding.
830                  */
831                 enlarge : function( unit, excludeBrs )
832                 {
833                         switch ( unit )
834                         {
835                                 case CKEDITOR.ENLARGE_ELEMENT :
837                                         if ( this.collapsed )
838                                                 return;
840                                         // Get the common ancestor.
841                                         var commonAncestor = this.getCommonAncestor();
843                                         var body = this.document.getBody();
845                                         // For each boundary
846                                         //              a. Depending on its position, find out the first node to be checked (a sibling) or, if not available, to be enlarge.
847                                         //              b. Go ahead checking siblings and enlarging the boundary as much as possible until the common ancestor is not reached. After reaching the common ancestor, just save the enlargeable node to be used later.
849                                         var startTop, endTop;
851                                         var enlargeable, sibling, commonReached;
853                                         // Indicates that the node can be added only if whitespace
854                                         // is available before it.
855                                         var needsWhiteSpace = false;
856                                         var isWhiteSpace;
857                                         var siblingText;
859                                         // Process the start boundary.
861                                         var container = this.startContainer;
862                                         var offset = this.startOffset;
864                                         if ( container.type == CKEDITOR.NODE_TEXT )
865                                         {
866                                                 if ( offset )
867                                                 {
868                                                         // Check if there is any non-space text before the
869                                                         // offset. Otherwise, container is null.
870                                                         container = !CKEDITOR.tools.trim( container.substring( 0, offset ) ).length && container;
872                                                         // If we found only whitespace in the node, it
873                                                         // means that we'll need more whitespace to be able
874                                                         // to expand. For example, <i> can be expanded in
875                                                         // "A <i> [B]</i>", but not in "A<i> [B]</i>".
876                                                         needsWhiteSpace = !!container;
877                                                 }
879                                                 if ( container )
880                                                 {
881                                                         if ( !( sibling = container.getPrevious() ) )
882                                                                 enlargeable = container.getParent();
883                                                 }
884                                         }
885                                         else
886                                         {
887                                                 // If we have offset, get the node preceeding it as the
888                                                 // first sibling to be checked.
889                                                 if ( offset )
890                                                         sibling = container.getChild( offset - 1 ) || container.getLast();
892                                                 // If there is no sibling, mark the container to be
893                                                 // enlarged.
894                                                 if ( !sibling )
895                                                         enlargeable = container;
896                                         }
898                                         while ( enlargeable || sibling )
899                                         {
900                                                 if ( enlargeable && !sibling )
901                                                 {
902                                                         // If we reached the common ancestor, mark the flag
903                                                         // for it.
904                                                         if ( !commonReached && enlargeable.equals( commonAncestor ) )
905                                                                 commonReached = true;
907                                                         if ( !body.contains( enlargeable ) )
908                                                                 break;
910                                                         // If we don't need space or this element breaks
911                                                         // the line, then enlarge it.
912                                                         if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' )
913                                                         {
914                                                                 needsWhiteSpace = false;
916                                                                 // If the common ancestor has been reached,
917                                                                 // we'll not enlarge it immediately, but just
918                                                                 // mark it to be enlarged later if the end
919                                                                 // boundary also enlarges it.
920                                                                 if ( commonReached )
921                                                                         startTop = enlargeable;
922                                                                 else
923                                                                         this.setStartBefore( enlargeable );
924                                                         }
926                                                         sibling = enlargeable.getPrevious();
927                                                 }
929                                                 // Check all sibling nodes preceeding the enlargeable
930                                                 // node. The node wil lbe enlarged only if none of them
931                                                 // blocks it.
932                                                 while ( sibling )
933                                                 {
934                                                         // This flag indicates that this node has
935                                                         // whitespaces at the end.
936                                                         isWhiteSpace = false;
938                                                         if ( sibling.type == CKEDITOR.NODE_TEXT )
939                                                         {
940                                                                 siblingText = sibling.getText();
942                                                                 if ( /[^\s\ufeff]/.test( siblingText ) )
943                                                                         sibling = null;
945                                                                 isWhiteSpace = /[\s\ufeff]$/.test( siblingText );
946                                                         }
947                                                         else
948                                                         {
949                                                                 // If this is a visible element.
950                                                                 // We need to check for the bookmark attribute because IE insists on
951                                                                 // rendering the display:none nodes we use for bookmarks. (#3363)
952                                                                 // Line-breaks (br) are rendered with zero width, which we don't want to include. (#7041)
953                                                                 if ( ( sibling.$.offsetWidth > 0 || excludeBrs && sibling.is( 'br' ) ) && !sibling.data( 'cke-bookmark' ) )
954                                                                 {
955                                                                         // We'll accept it only if we need
956                                                                         // whitespace, and this is an inline
957                                                                         // element with whitespace only.
958                                                                         if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] )
959                                                                         {
960                                                                                 // It must contains spaces and inline elements only.
962                                                                                 siblingText = sibling.getText();
964                                                                                 if ( (/[^\s\ufeff]/).test( siblingText ) )      // Spaces + Zero Width No-Break Space (U+FEFF)
965                                                                                         sibling = null;
966                                                                                 else
967                                                                                 {
968                                                                                         var allChildren = sibling.$.all || sibling.$.getElementsByTagName( '*' );
969                                                                                         for ( var i = 0, child ; child = allChildren[ i++ ] ; )
970                                                                                         {
971                                                                                                 if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] )
972                                                                                                 {
973                                                                                                         sibling = null;
974                                                                                                         break;
975                                                                                                 }
976                                                                                         }
977                                                                                 }
979                                                                                 if ( sibling )
980                                                                                         isWhiteSpace = !!siblingText.length;
981                                                                         }
982                                                                         else
983                                                                                 sibling = null;
984                                                                 }
985                                                         }
987                                                         // A node with whitespaces has been found.
988                                                         if ( isWhiteSpace )
989                                                         {
990                                                                 // Enlarge the last enlargeable node, if we
991                                                                 // were waiting for spaces.
992                                                                 if ( needsWhiteSpace )
993                                                                 {
994                                                                         if ( commonReached )
995                                                                                 startTop = enlargeable;
996                                                                         else if ( enlargeable )
997                                                                                 this.setStartBefore( enlargeable );
998                                                                 }
999                                                                 else
1000                                                                         needsWhiteSpace = true;
1001                                                         }
1003                                                         if ( sibling )
1004                                                         {
1005                                                                 var next = sibling.getPrevious();
1007                                                                 if ( !enlargeable && !next )
1008                                                                 {
1009                                                                         // Set the sibling as enlargeable, so it's
1010                                                                         // parent will be get later outside this while.
1011                                                                         enlargeable = sibling;
1012                                                                         sibling = null;
1013                                                                         break;
1014                                                                 }
1016                                                                 sibling = next;
1017                                                         }
1018                                                         else
1019                                                         {
1020                                                                 // If sibling has been set to null, then we
1021                                                                 // need to stop enlarging.
1022                                                                 enlargeable = null;
1023                                                         }
1024                                                 }
1026                                                 if ( enlargeable )
1027                                                         enlargeable = enlargeable.getParent();
1028                                         }
1030                                         // Process the end boundary. This is basically the same
1031                                         // code used for the start boundary, with small changes to
1032                                         // make it work in the oposite side (to the right). This
1033                                         // makes it difficult to reuse the code here. So, fixes to
1034                                         // the above code are likely to be replicated here.
1036                                         container = this.endContainer;
1037                                         offset = this.endOffset;
1039                                         // Reset the common variables.
1040                                         enlargeable = sibling = null;
1041                                         commonReached = needsWhiteSpace = false;
1043                                         if ( container.type == CKEDITOR.NODE_TEXT )
1044                                         {
1045                                                 // Check if there is any non-space text after the
1046                                                 // offset. Otherwise, container is null.
1047                                                 container = !CKEDITOR.tools.trim( container.substring( offset ) ).length && container;
1049                                                 // If we found only whitespace in the node, it
1050                                                 // means that we'll need more whitespace to be able
1051                                                 // to expand. For example, <i> can be expanded in
1052                                                 // "A <i> [B]</i>", but not in "A<i> [B]</i>".
1053                                                 needsWhiteSpace = !( container && container.getLength() );
1055                                                 if ( container )
1056                                                 {
1057                                                         if ( !( sibling = container.getNext() ) )
1058                                                                 enlargeable = container.getParent();
1059                                                 }
1060                                         }
1061                                         else
1062                                         {
1063                                                 // Get the node right after the boudary to be checked
1064                                                 // first.
1065                                                 sibling = container.getChild( offset );
1067                                                 if ( !sibling )
1068                                                         enlargeable = container;
1069                                         }
1071                                         while ( enlargeable || sibling )
1072                                         {
1073                                                 if ( enlargeable && !sibling )
1074                                                 {
1075                                                         if ( !commonReached && enlargeable.equals( commonAncestor ) )
1076                                                                 commonReached = true;
1078                                                         if ( !body.contains( enlargeable ) )
1079                                                                 break;
1081                                                         if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' )
1082                                                         {
1083                                                                 needsWhiteSpace = false;
1085                                                                 if ( commonReached )
1086                                                                         endTop = enlargeable;
1087                                                                 else if ( enlargeable )
1088                                                                         this.setEndAfter( enlargeable );
1089                                                         }
1091                                                         sibling = enlargeable.getNext();
1092                                                 }
1094                                                 while ( sibling )
1095                                                 {
1096                                                         isWhiteSpace = false;
1098                                                         if ( sibling.type == CKEDITOR.NODE_TEXT )
1099                                                         {
1100                                                                 siblingText = sibling.getText();
1102                                                                 if ( /[^\s\ufeff]/.test( siblingText ) )
1103                                                                         sibling = null;
1105                                                                 isWhiteSpace = /^[\s\ufeff]/.test( siblingText );
1106                                                         }
1107                                                         else
1108                                                         {
1109                                                                 // If this is a visible element.
1110                                                                 // We need to check for the bookmark attribute because IE insists on
1111                                                                 // rendering the display:none nodes we use for bookmarks. (#3363)
1112                                                                 // Line-breaks (br) are rendered with zero width, which we don't want to include. (#7041)
1113                                                                 if ( ( sibling.$.offsetWidth > 0 || excludeBrs && sibling.is( 'br' ) ) && !sibling.data( 'cke-bookmark' ) )
1114                                                                 {
1115                                                                         // We'll accept it only if we need
1116                                                                         // whitespace, and this is an inline
1117                                                                         // element with whitespace only.
1118                                                                         if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] )
1119                                                                         {
1120                                                                                 // It must contains spaces and inline elements only.
1122                                                                                 siblingText = sibling.getText();
1124                                                                                 if ( (/[^\s\ufeff]/).test( siblingText ) )
1125                                                                                         sibling = null;
1126                                                                                 else
1127                                                                                 {
1128                                                                                         allChildren = sibling.$.all || sibling.$.getElementsByTagName( '*' );
1129                                                                                         for ( i = 0 ; child = allChildren[ i++ ] ; )
1130                                                                                         {
1131                                                                                                 if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] )
1132                                                                                                 {
1133                                                                                                         sibling = null;
1134                                                                                                         break;
1135                                                                                                 }
1136                                                                                         }
1137                                                                                 }
1139                                                                                 if ( sibling )
1140                                                                                         isWhiteSpace = !!siblingText.length;
1141                                                                         }
1142                                                                         else
1143                                                                                 sibling = null;
1144                                                                 }
1145                                                         }
1147                                                         if ( isWhiteSpace )
1148                                                         {
1149                                                                 if ( needsWhiteSpace )
1150                                                                 {
1151                                                                         if ( commonReached )
1152                                                                                 endTop = enlargeable;
1153                                                                         else
1154                                                                                 this.setEndAfter( enlargeable );
1155                                                                 }
1156                                                         }
1158                                                         if ( sibling )
1159                                                         {
1160                                                                 next = sibling.getNext();
1162                                                                 if ( !enlargeable && !next )
1163                                                                 {
1164                                                                         enlargeable = sibling;
1165                                                                         sibling = null;
1166                                                                         break;
1167                                                                 }
1169                                                                 sibling = next;
1170                                                         }
1171                                                         else
1172                                                         {
1173                                                                 // If sibling has been set to null, then we
1174                                                                 // need to stop enlarging.
1175                                                                 enlargeable = null;
1176                                                         }
1177                                                 }
1179                                                 if ( enlargeable )
1180                                                         enlargeable = enlargeable.getParent();
1181                                         }
1183                                         // If the common ancestor can be enlarged by both boundaries, then include it also.
1184                                         if ( startTop && endTop )
1185                                         {
1186                                                 commonAncestor = startTop.contains( endTop ) ? endTop : startTop;
1188                                                 this.setStartBefore( commonAncestor );
1189                                                 this.setEndAfter( commonAncestor );
1190                                         }
1191                                         break;
1193                                 case CKEDITOR.ENLARGE_BLOCK_CONTENTS:
1194                                 case CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS:
1196                                         // Enlarging the start boundary.
1197                                         var walkerRange = new CKEDITOR.dom.range( this.document );
1199                                         body = this.document.getBody();
1201                                         walkerRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START );
1202                                         walkerRange.setEnd( this.startContainer, this.startOffset );
1204                                         var walker = new CKEDITOR.dom.walker( walkerRange ),
1205                                             blockBoundary,  // The node on which the enlarging should stop.
1206                                                 tailBr, // In case BR as block boundary.
1207                                             notBlockBoundary = CKEDITOR.dom.walker.blockBoundary(
1208                                                                 ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ? { br : 1 } : null ),
1209                                                 // Record the encountered 'blockBoundary' for later use.
1210                                                 boundaryGuard = function( node )
1211                                                 {
1212                                                         var retval = notBlockBoundary( node );
1213                                                         if ( !retval )
1214                                                                 blockBoundary = node;
1215                                                         return retval;
1216                                                 },
1217                                                 // Record the encounted 'tailBr' for later use.
1218                                                 tailBrGuard = function( node )
1219                                                 {
1220                                                         var retval = boundaryGuard( node );
1221                                                         if ( !retval && node.is && node.is( 'br' ) )
1222                                                                 tailBr = node;
1223                                                         return retval;
1224                                                 };
1226                                         walker.guard = boundaryGuard;
1228                                         enlargeable = walker.lastBackward();
1230                                         // It's the body which stop the enlarging if no block boundary found.
1231                                         blockBoundary = blockBoundary || body;
1233                                         // Start the range either after the end of found block (<p>...</p>[text)
1234                                         // or at the start of block (<p>[text...), by comparing the document position
1235                                         // with 'enlargeable' node.
1236                                         this.setStartAt(
1237                                                         blockBoundary,
1238                                                         !blockBoundary.is( 'br' ) &&
1239                                                         ( !enlargeable && this.checkStartOfBlock()
1240                                                           || enlargeable && blockBoundary.contains( enlargeable ) ) ?
1241                                                                 CKEDITOR.POSITION_AFTER_START :
1242                                                                 CKEDITOR.POSITION_AFTER_END );
1244                                         // Enlarging the end boundary.
1245                                         walkerRange = this.clone();
1246                                         walkerRange.collapse();
1247                                         walkerRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
1248                                         walker = new CKEDITOR.dom.walker( walkerRange );
1250                                         // tailBrGuard only used for on range end.
1251                                         walker.guard = ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ?
1252                                                 tailBrGuard : boundaryGuard;
1253                                         blockBoundary = null;
1254                                         // End the range right before the block boundary node.
1256                                         enlargeable = walker.lastForward();
1258                                         // It's the body which stop the enlarging if no block boundary found.
1259                                         blockBoundary = blockBoundary || body;
1261                                         // Close the range either before the found block start (text]<p>...</p>) or at the block end (...text]</p>)
1262                                         // by comparing the document position with 'enlargeable' node.
1263                                         this.setEndAt(
1264                                                         blockBoundary,
1265                                                         ( !enlargeable && this.checkEndOfBlock()
1266                                                           || enlargeable && blockBoundary.contains( enlargeable ) ) ?
1267                                                                 CKEDITOR.POSITION_BEFORE_END :
1268                                                                 CKEDITOR.POSITION_BEFORE_START );
1269                                         // We must include the <br> at the end of range if there's
1270                                         // one and we're expanding list item contents
1271                                         if ( tailBr )
1272                                                 this.setEndAfter( tailBr );
1273                         }
1274                 },
1276                 /**
1277                  *  Descrease the range to make sure that boundaries
1278                 *  always anchor beside text nodes or innermost element.
1279                  * @param {Number} mode  ( CKEDITOR.SHRINK_ELEMENT | CKEDITOR.SHRINK_TEXT ) The shrinking mode.
1280                  * <dl>
1281                  *       <dt>CKEDITOR.SHRINK_ELEMENT</dt>
1282                  *       <dd>Shrink the range boundaries to the edge of the innermost element.</dd>
1283                  *       <dt>CKEDITOR.SHRINK_TEXT</dt>
1284                  *       <dd>Shrink the range boudaries to anchor by the side of enclosed text  node, range remains if there's no text nodes on boundaries at all.</dd>
1285                   * </dl>
1286                  * @param {Boolean} selectContents Whether result range anchors at the inner OR outer boundary of the node.
1287                  */
1288                 shrink : function( mode, selectContents )
1289                 {
1290                         // Unable to shrink a collapsed range.
1291                         if ( !this.collapsed )
1292                         {
1293                                 mode = mode || CKEDITOR.SHRINK_TEXT;
1295                                 var walkerRange = this.clone();
1297                                 var startContainer = this.startContainer,
1298                                         endContainer = this.endContainer,
1299                                         startOffset = this.startOffset,
1300                                         endOffset = this.endOffset,
1301                                         collapsed = this.collapsed;
1303                                 // Whether the start/end boundary is moveable.
1304                                 var moveStart = 1,
1305                                                 moveEnd = 1;
1307                                 if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
1308                                 {
1309                                         if ( !startOffset )
1310                                                 walkerRange.setStartBefore( startContainer );
1311                                         else if ( startOffset >= startContainer.getLength( ) )
1312                                                 walkerRange.setStartAfter( startContainer );
1313                                         else
1314                                         {
1315                                                 // Enlarge the range properly to avoid walker making
1316                                                 // DOM changes caused by triming the text nodes later.
1317                                                 walkerRange.setStartBefore( startContainer );
1318                                                 moveStart = 0;
1319                                         }
1320                                 }
1322                                 if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
1323                                 {
1324                                         if ( !endOffset )
1325                                                 walkerRange.setEndBefore( endContainer );
1326                                         else if ( endOffset >= endContainer.getLength( ) )
1327                                                 walkerRange.setEndAfter( endContainer );
1328                                         else
1329                                         {
1330                                                 walkerRange.setEndAfter( endContainer );
1331                                                 moveEnd = 0;
1332                                         }
1333                                 }
1335                                 var walker = new CKEDITOR.dom.walker( walkerRange ),
1336                                         isBookmark = CKEDITOR.dom.walker.bookmark();
1338                                 walker.evaluator = function( node )
1339                                 {
1340                                         return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ?
1341                                                 CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT );
1342                                 };
1344                                 var currentElement;
1345                                 walker.guard = function( node, movingOut )
1346                                 {
1347                                         if ( isBookmark( node ) )
1348                                                 return true;
1350                                         // Stop when we're shrink in element mode while encountering a text node.
1351                                         if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT )
1352                                                 return false;
1354                                         // Stop when we've already walked "through" an element.
1355                                         if ( movingOut && node.equals( currentElement ) )
1356                                                 return false;
1358                                         if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT )
1359                                                 currentElement = node;
1361                                         return true;
1362                                 };
1364                                 if ( moveStart )
1365                                 {
1366                                         var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next']();
1367                                         textStart && this.setStartAt( textStart, selectContents ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_START );
1368                                 }
1370                                 if ( moveEnd )
1371                                 {
1372                                         walker.reset();
1373                                         var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous']();
1374                                         textEnd && this.setEndAt( textEnd, selectContents ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_END );
1375                                 }
1377                                 return !!( moveStart || moveEnd );
1378                         }
1379                 },
1381                 /**
1382                  * Inserts a node at the start of the range. The range will be expanded
1383                  * the contain the node.
1384                  */
1385                 insertNode : function( node )
1386                 {
1387                         this.optimizeBookmark();
1388                         this.trim( false, true );
1390                         var startContainer = this.startContainer;
1391                         var startOffset = this.startOffset;
1393                         var nextNode = startContainer.getChild( startOffset );
1395                         if ( nextNode )
1396                                 node.insertBefore( nextNode );
1397                         else
1398                                 startContainer.append( node );
1400                         // Check if we need to update the end boundary.
1401                         if ( node.getParent().equals( this.endContainer ) )
1402                                 this.endOffset++;
1404                         // Expand the range to embrace the new node.
1405                         this.setStartBefore( node );
1406                 },
1408                 moveToPosition : function( node, position )
1409                 {
1410                         this.setStartAt( node, position );
1411                         this.collapse( true );
1412                 },
1414                 selectNodeContents : function( node )
1415                 {
1416                         this.setStart( node, 0 );
1417                         this.setEnd( node, node.type == CKEDITOR.NODE_TEXT ? node.getLength() : node.getChildCount() );
1418                 },
1420                 /**
1421                  * Sets the start position of a Range.
1422                  * @param {CKEDITOR.dom.node} startNode The node to start the range.
1423                  * @param {Number} startOffset An integer greater than or equal to zero
1424                  *              representing the offset for the start of the range from the start
1425                  *              of startNode.
1426                  */
1427                 setStart : function( startNode, startOffset )
1428                 {
1429                         // W3C requires a check for the new position. If it is after the end
1430                         // boundary, the range should be collapsed to the new start. It seams
1431                         // we will not need this check for our use of this class so we can
1432                         // ignore it for now.
1434                         // Fixing invalid range start inside dtd empty elements.
1435                         if( startNode.type == CKEDITOR.NODE_ELEMENT
1436                                 && CKEDITOR.dtd.$empty[ startNode.getName() ] )
1437                                 startOffset = startNode.getIndex(), startNode = startNode.getParent();
1439                         this.startContainer     = startNode;
1440                         this.startOffset        = startOffset;
1442                         if ( !this.endContainer )
1443                         {
1444                                 this.endContainer       = startNode;
1445                                 this.endOffset          = startOffset;
1446                         }
1448                         updateCollapsed( this );
1449                 },
1451                 /**
1452                  * Sets the end position of a Range.
1453                  * @param {CKEDITOR.dom.node} endNode The node to end the range.
1454                  * @param {Number} endOffset An integer greater than or equal to zero
1455                  *              representing the offset for the end of the range from the start
1456                  *              of endNode.
1457                  */
1458                 setEnd : function( endNode, endOffset )
1459                 {
1460                         // W3C requires a check for the new position. If it is before the start
1461                         // boundary, the range should be collapsed to the new end. It seams we
1462                         // will not need this check for our use of this class so we can ignore
1463                         // it for now.
1465                         // Fixing invalid range end inside dtd empty elements.
1466                         if( endNode.type == CKEDITOR.NODE_ELEMENT
1467                                 && CKEDITOR.dtd.$empty[ endNode.getName() ] )
1468                                 endOffset = endNode.getIndex() + 1, endNode = endNode.getParent();
1470                         this.endContainer       = endNode;
1471                         this.endOffset          = endOffset;
1473                         if ( !this.startContainer )
1474                         {
1475                                 this.startContainer     = endNode;
1476                                 this.startOffset        = endOffset;
1477                         }
1479                         updateCollapsed( this );
1480                 },
1482                 setStartAfter : function( node )
1483                 {
1484                         this.setStart( node.getParent(), node.getIndex() + 1 );
1485                 },
1487                 setStartBefore : function( node )
1488                 {
1489                         this.setStart( node.getParent(), node.getIndex() );
1490                 },
1492                 setEndAfter : function( node )
1493                 {
1494                         this.setEnd( node.getParent(), node.getIndex() + 1 );
1495                 },
1497                 setEndBefore : function( node )
1498                 {
1499                         this.setEnd( node.getParent(), node.getIndex() );
1500                 },
1502                 setStartAt : function( node, position )
1503                 {
1504                         switch( position )
1505                         {
1506                                 case CKEDITOR.POSITION_AFTER_START :
1507                                         this.setStart( node, 0 );
1508                                         break;
1510                                 case CKEDITOR.POSITION_BEFORE_END :
1511                                         if ( node.type == CKEDITOR.NODE_TEXT )
1512                                                 this.setStart( node, node.getLength() );
1513                                         else
1514                                                 this.setStart( node, node.getChildCount() );
1515                                         break;
1517                                 case CKEDITOR.POSITION_BEFORE_START :
1518                                         this.setStartBefore( node );
1519                                         break;
1521                                 case CKEDITOR.POSITION_AFTER_END :
1522                                         this.setStartAfter( node );
1523                         }
1525                         updateCollapsed( this );
1526                 },
1528                 setEndAt : function( node, position )
1529                 {
1530                         switch( position )
1531                         {
1532                                 case CKEDITOR.POSITION_AFTER_START :
1533                                         this.setEnd( node, 0 );
1534                                         break;
1536                                 case CKEDITOR.POSITION_BEFORE_END :
1537                                         if ( node.type == CKEDITOR.NODE_TEXT )
1538                                                 this.setEnd( node, node.getLength() );
1539                                         else
1540                                                 this.setEnd( node, node.getChildCount() );
1541                                         break;
1543                                 case CKEDITOR.POSITION_BEFORE_START :
1544                                         this.setEndBefore( node );
1545                                         break;
1547                                 case CKEDITOR.POSITION_AFTER_END :
1548                                         this.setEndAfter( node );
1549                         }
1551                         updateCollapsed( this );
1552                 },
1554                 fixBlock : function( isStart, blockTag )
1555                 {
1556                         var bookmark = this.createBookmark(),
1557                                 fixedBlock = this.document.createElement( blockTag );
1559                         this.collapse( isStart );
1561                         this.enlarge( CKEDITOR.ENLARGE_BLOCK_CONTENTS );
1563                         this.extractContents().appendTo( fixedBlock );
1564                         fixedBlock.trim();
1566                         if ( !CKEDITOR.env.ie )
1567                                 fixedBlock.appendBogus();
1569                         this.insertNode( fixedBlock );
1571                         this.moveToBookmark( bookmark );
1573                         return fixedBlock;
1574                 },
1576                 splitBlock : function( blockTag )
1577                 {
1578                         var startPath   = new CKEDITOR.dom.elementPath( this.startContainer ),
1579                                 endPath         = new CKEDITOR.dom.elementPath( this.endContainer );
1581                         var startBlockLimit     = startPath.blockLimit,
1582                                 endBlockLimit   = endPath.blockLimit;
1584                         var startBlock  = startPath.block,
1585                                 endBlock        = endPath.block;
1587                         var elementPath = null;
1588                         // Do nothing if the boundaries are in different block limits.
1589                         if ( !startBlockLimit.equals( endBlockLimit ) )
1590                                 return null;
1592                         // Get or fix current blocks.
1593                         if ( blockTag != 'br' )
1594                         {
1595                                 if ( !startBlock )
1596                                 {
1597                                         startBlock = this.fixBlock( true, blockTag );
1598                                         endBlock = new CKEDITOR.dom.elementPath( this.endContainer ).block;
1599                                 }
1601                                 if ( !endBlock )
1602                                         endBlock = this.fixBlock( false, blockTag );
1603                         }
1605                         // Get the range position.
1606                         var isStartOfBlock = startBlock && this.checkStartOfBlock(),
1607                                 isEndOfBlock = endBlock && this.checkEndOfBlock();
1609                         // Delete the current contents.
1610                         // TODO: Why is 2.x doing CheckIsEmpty()?
1611                         this.deleteContents();
1613                         if ( startBlock && startBlock.equals( endBlock ) )
1614                         {
1615                                 if ( isEndOfBlock )
1616                                 {
1617                                         elementPath = new CKEDITOR.dom.elementPath( this.startContainer );
1618                                         this.moveToPosition( endBlock, CKEDITOR.POSITION_AFTER_END );
1619                                         endBlock = null;
1620                                 }
1621                                 else if ( isStartOfBlock )
1622                                 {
1623                                         elementPath = new CKEDITOR.dom.elementPath( this.startContainer );
1624                                         this.moveToPosition( startBlock, CKEDITOR.POSITION_BEFORE_START );
1625                                         startBlock = null;
1626                                 }
1627                                 else
1628                                 {
1629                                         endBlock = this.splitElement( startBlock );
1631                                         // In Gecko, the last child node must be a bogus <br>.
1632                                         // Note: bogus <br> added under <ul> or <ol> would cause
1633                                         // lists to be incorrectly rendered.
1634                                         if ( !CKEDITOR.env.ie && !startBlock.is( 'ul', 'ol') )
1635                                                 startBlock.appendBogus() ;
1636                                 }
1637                         }
1639                         return {
1640                                 previousBlock : startBlock,
1641                                 nextBlock : endBlock,
1642                                 wasStartOfBlock : isStartOfBlock,
1643                                 wasEndOfBlock : isEndOfBlock,
1644                                 elementPath : elementPath
1645                         };
1646                 },
1648                 /**
1649                  * Branch the specified element from the collapsed range position and
1650                  * place the caret between the two result branches.
1651                  * Note: The range must be collapsed and been enclosed by this element.
1652                  * @param {CKEDITOR.dom.element} element
1653                  * @return {CKEDITOR.dom.element} Root element of the new branch after the split.
1654                  */
1655                 splitElement : function( toSplit )
1656                 {
1657                         if ( !this.collapsed )
1658                                 return null;
1660                         // Extract the contents of the block from the selection point to the end
1661                         // of its contents.
1662                         this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END );
1663                         var documentFragment = this.extractContents();
1665                         // Duplicate the element after it.
1666                         var clone = toSplit.clone( false );
1668                         // Place the extracted contents into the duplicated element.
1669                         documentFragment.appendTo( clone );
1670                         clone.insertAfter( toSplit );
1671                         this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END );
1672                         return clone;
1673                 },
1675                 /**
1676                  * Check whether a range boundary is at the inner boundary of a given
1677                  * element.
1678                  * @param {CKEDITOR.dom.element} element The target element to check.
1679                  * @param {Number} checkType The boundary to check for both the range
1680                  *              and the element. It can be CKEDITOR.START or CKEDITOR.END.
1681                  * @returns {Boolean} "true" if the range boundary is at the inner
1682                  *              boundary of the element.
1683                  */
1684                 checkBoundaryOfElement : function( element, checkType )
1685                 {
1686                         var checkStart = ( checkType == CKEDITOR.START );
1688                         // Create a copy of this range, so we can manipulate it for our checks.
1689                         var walkerRange = this.clone();
1691                         // Collapse the range at the proper size.
1692                         walkerRange.collapse( checkStart );
1694                         // Expand the range to element boundary.
1695                         walkerRange[ checkStart ? 'setStartAt' : 'setEndAt' ]
1696                          ( element, checkStart ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_END );
1698                         // Create the walker, which will check if we have anything useful
1699                         // in the range.
1700                         var walker = new CKEDITOR.dom.walker( walkerRange );
1701                         walker.evaluator = elementBoundaryEval;
1703                         return walker[ checkStart ? 'checkBackward' : 'checkForward' ]();
1704                 },
1706                 // Calls to this function may produce changes to the DOM. The range may
1707                 // be updated to reflect such changes.
1708                 checkStartOfBlock : function()
1709                 {
1710                         var startContainer = this.startContainer,
1711                                 startOffset = this.startOffset;
1713                         // If the starting node is a text node, and non-empty before the offset,
1714                         // then we're surely not at the start of block.
1715                         if ( startOffset && startContainer.type == CKEDITOR.NODE_TEXT )
1716                         {
1717                                 var textBefore = CKEDITOR.tools.ltrim( startContainer.substring( 0, startOffset ) );
1718                                 if ( textBefore.length )
1719                                         return false;
1720                         }
1722                         // Antecipate the trim() call here, so the walker will not make
1723                         // changes to the DOM, which would not get reflected into this
1724                         // range otherwise.
1725                         this.trim();
1727                         // We need to grab the block element holding the start boundary, so
1728                         // let's use an element path for it.
1729                         var path = new CKEDITOR.dom.elementPath( this.startContainer );
1731                         // Creates a range starting at the block start until the range start.
1732                         var walkerRange = this.clone();
1733                         walkerRange.collapse( true );
1734                         walkerRange.setStartAt( path.block || path.blockLimit, CKEDITOR.POSITION_AFTER_START );
1736                         var walker = new CKEDITOR.dom.walker( walkerRange );
1737                         walker.evaluator = getCheckStartEndBlockEvalFunction( true );
1739                         return walker.checkBackward();
1740                 },
1742                 checkEndOfBlock : function()
1743                 {
1744                         var endContainer = this.endContainer,
1745                                 endOffset = this.endOffset;
1747                         // If the ending node is a text node, and non-empty after the offset,
1748                         // then we're surely not at the end of block.
1749                         if ( endContainer.type == CKEDITOR.NODE_TEXT )
1750                         {
1751                                 var textAfter = CKEDITOR.tools.rtrim( endContainer.substring( endOffset ) );
1752                                 if ( textAfter.length )
1753                                         return false;
1754                         }
1756                         // Antecipate the trim() call here, so the walker will not make
1757                         // changes to the DOM, which would not get reflected into this
1758                         // range otherwise.
1759                         this.trim();
1761                         // We need to grab the block element holding the start boundary, so
1762                         // let's use an element path for it.
1763                         var path = new CKEDITOR.dom.elementPath( this.endContainer );
1765                         // Creates a range starting at the block start until the range start.
1766                         var walkerRange = this.clone();
1767                         walkerRange.collapse( false );
1768                         walkerRange.setEndAt( path.block || path.blockLimit, CKEDITOR.POSITION_BEFORE_END );
1770                         var walker = new CKEDITOR.dom.walker( walkerRange );
1771                         walker.evaluator = getCheckStartEndBlockEvalFunction( false );
1773                         return walker.checkForward();
1774                 },
1776                 /**
1777                  * Check if elements at which the range boundaries anchor are read-only,
1778                  * with respect to "contenteditable" attribute.
1779                  */
1780                 checkReadOnly : ( function()
1781                 {
1782                         function checkNodesEditable( node, anotherEnd )
1783                         {
1784                                 while( node )
1785                                 {
1786                                         if ( node.type == CKEDITOR.NODE_ELEMENT )
1787                                         {
1788                                                 if ( node.getAttribute( 'contentEditable' ) == 'false'
1789                                                         && !node.data( 'cke-editable' ) )
1790                                                 {
1791                                                         return 0;
1792                                                 }
1793                                                 // Range enclosed entirely in an editable element.
1794                                                 else if ( node.is( 'body' )
1795                                                         || node.getAttribute( 'contentEditable' ) == 'true'
1796                                                         && ( node.contains( anotherEnd ) || node.equals( anotherEnd ) ) )
1797                                                 {
1798                                                         break;
1799                                                 }
1800                                         }
1801                                         node = node.getParent();
1802                                 }
1804                                 return 1;
1805                         }
1807                         return function()
1808                         {
1809                                 var startNode = this.startContainer,
1810                                         endNode = this.endContainer;
1812                                 // Check if elements path at both boundaries are editable.
1813                                 return !( checkNodesEditable( startNode, endNode ) && checkNodesEditable( endNode, startNode ) );
1814                         };
1815                 })(),
1817                 /**
1818                  * Moves the range boundaries to the first/end editing point inside an
1819                  * element. For example, in an element tree like
1820                  * "&lt;p&gt;&lt;b&gt;&lt;i&gt;&lt;/i&gt;&lt;/b&gt; Text&lt;/p&gt;", the start editing point is
1821                  * "&lt;p&gt;&lt;b&gt;&lt;i&gt;^&lt;/i&gt;&lt;/b&gt; Text&lt;/p&gt;" (inside &lt;i&gt;).
1822                  * @param {CKEDITOR.dom.element} el The element into which look for the
1823                  *              editing spot.
1824                  * @param {Boolean} isMoveToEnd Whether move to the end editable position.
1825                  */
1826                 moveToElementEditablePosition : function( el, isMoveToEnd )
1827                 {
1828                         var isEditable;
1830                         // Empty elements are rejected.
1831                         if ( CKEDITOR.dtd.$empty[ el.getName() ] )
1832                                 return false;
1834                         while ( el && el.type == CKEDITOR.NODE_ELEMENT )
1835                         {
1836                                 isEditable = el.isEditable();
1838                                 // If an editable element is found, move inside it.
1839                                 if ( isEditable )
1840                                         this.moveToPosition( el, isMoveToEnd ?
1841                                                                  CKEDITOR.POSITION_BEFORE_END :
1842                                                                  CKEDITOR.POSITION_AFTER_START );
1843                                 // Stop immediately if we've found a non editable inline element (e.g <img>).
1844                                 else if ( CKEDITOR.dtd.$inline[ el.getName() ] )
1845                                 {
1846                                         this.moveToPosition( el, isMoveToEnd ?
1847                                                                  CKEDITOR.POSITION_AFTER_END :
1848                                                                  CKEDITOR.POSITION_BEFORE_START );
1849                                         return true;
1850                                 }
1852                                 // Non-editable non-inline elements are to be bypassed, getting the next one.
1853                                 if ( CKEDITOR.dtd.$empty[ el.getName() ] )
1854                                         el = el[ isMoveToEnd ? 'getPrevious' : 'getNext' ]( nonWhitespaceOrBookmarkEval );
1855                                 else
1856                                         el = el[ isMoveToEnd ? 'getLast' : 'getFirst' ]( nonWhitespaceOrBookmarkEval );
1858                                 // Stop immediately if we've found a text node.
1859                                 if ( el && el.type == CKEDITOR.NODE_TEXT )
1860                                 {
1861                                         this.moveToPosition( el, isMoveToEnd ?
1862                                                                  CKEDITOR.POSITION_AFTER_END :
1863                                                                  CKEDITOR.POSITION_BEFORE_START );
1864                                         return true;
1865                                 }
1866                         }
1868                         return isEditable;
1869                 },
1871                 /**
1872                  *@see {CKEDITOR.dom.range.moveToElementEditablePosition}
1873                  */
1874                 moveToElementEditStart : function( target )
1875                 {
1876                         return this.moveToElementEditablePosition( target );
1877                 },
1879                 /**
1880                  *@see {CKEDITOR.dom.range.moveToElementEditablePosition}
1881                  */
1882                 moveToElementEditEnd : function( target )
1883                 {
1884                         return this.moveToElementEditablePosition( target, true );
1885                 },
1887                 /**
1888                  * Get the single node enclosed within the range if there's one.
1889                  */
1890                 getEnclosedNode : function()
1891                 {
1892                         var walkerRange = this.clone();
1894                         // Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780)
1895                         walkerRange.optimize();
1896                         if ( walkerRange.startContainer.type != CKEDITOR.NODE_ELEMENT
1897                                         || walkerRange.endContainer.type != CKEDITOR.NODE_ELEMENT )
1898                                 return null;
1900                         var walker = new CKEDITOR.dom.walker( walkerRange ),
1901                                 isNotBookmarks = CKEDITOR.dom.walker.bookmark( true ),
1902                                 isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
1903                                 evaluator = function( node )
1904                                 {
1905                                         return isNotWhitespaces( node ) && isNotBookmarks( node );
1906                                 };
1907                         walkerRange.evaluator = evaluator;
1908                         var node = walker.next();
1909                         walker.reset();
1910                         return node && node.equals( walker.previous() ) ? node : null;
1911                 },
1913                 getTouchedStartNode : function()
1914                 {
1915                         var container = this.startContainer ;
1917                         if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT )
1918                                 return container ;
1920                         return container.getChild( this.startOffset ) || container ;
1921                 },
1923                 getTouchedEndNode : function()
1924                 {
1925                         var container = this.endContainer ;
1927                         if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT )
1928                                 return container ;
1930                         return container.getChild( this.endOffset - 1 ) || container ;
1931                 }
1932         };
1933 })();
1935 CKEDITOR.POSITION_AFTER_START   = 1;    // <element>^contents</element>         "^text"
1936 CKEDITOR.POSITION_BEFORE_END    = 2;    // <element>contents^</element>         "text^"
1937 CKEDITOR.POSITION_BEFORE_START  = 3;    // ^<element>contents</element>         ^"text"
1938 CKEDITOR.POSITION_AFTER_END             = 4;    // <element>contents</element>^         "text"
1940 CKEDITOR.ENLARGE_ELEMENT = 1;
1941 CKEDITOR.ENLARGE_BLOCK_CONTENTS = 2;
1942 CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS = 3;
1944 // Check boundary types.
1945 // @see CKEDITOR.dom.range.prototype.checkBoundaryOfElement
1946 CKEDITOR.START = 1;
1947 CKEDITOR.END = 2;
1948 CKEDITOR.STARTEND = 3;
1950 // Shrink range types.
1951 // @see CKEDITOR.dom.range.prototype.shrink
1952 CKEDITOR.SHRINK_ELEMENT = 1;
1953 CKEDITOR.SHRINK_TEXT = 2;